Is frequent downcasting in class hierarchy always evil? - oop

From what I`ve learned, it is no good if you frequently use downcasting in class hierarchies.
I agree with that, but what are exceptions from this rule if any?
This is where my design of graphical editor shows thin: I have two hierarchies, where geometric figures hierarchy decoupled from graphic primitives one. Like this:
public class GeometricPrimitive {...}
public class RectangeGeometric: Geometric Primitive {...}
public class GraphicPrimitive {...}
public class Rectangle: GraphicPrimitive {
private RectangleGeometric figure;
...
}
So, every concrete graphic figure class encapsulates instance of concrete geometry class. Is that approach is the right one, or should I prefer more generical one? - unfortunately, downcasting would be used in this case:
public class GraphicPrimitive {
protected GeometryPrimitive figure;
....
}
public class Rectangle: GraohicPrimitive {
public Rectangle(Color c, TwoDPoint leftHighPoint, TwoDPoint rightLowPoint):
base(new RectangleGeometric(leftHighPoint.Point2D, rightLowPoint.Point2D), c) { }
#region Geometric Properties
public TwoDPoint LeftTopCorner {
get { return new TwoDPoint(base.color, (base.figure as RectangleGeometric).LeftTopCorner); }
}
public TwoDPoint RightBottomCorner {
get { return new TwoDPoint(base.color, (base.figure as RectangleGeometric).RightBottomCorner); }
}

While your question lacks some of the larger context about your application that would help with giving a specific answer, I'll try by giving you some ideas of how I would implement this using your code for inspiration.
I would start by inverting the relationship GeometryPrimitive and GraphicPrimitive. I see the the GeometryPrimitive hierarchy as the domain objects that make up your abstract scene graph and the GraphicPrimitive hierarchy as low level view components that translate a GeometryPrimitive into a set of pixels appropriate for drawing onto some kind of graphics context. The GeometryPrimitive subclasses hold all the state information necessary to describe themselves but no logic for translating that description into pixels. The GraphicPrimitive subclasses have all the pixel pushing logic, but no internal state. In effect, the GraphicPrimitive hierarchy represents a hierarchy of Command Objects.
In the GeometryPrimitive base class, include an abstract method called GetGraphicPrimitive(). In the GraphicPrimitive base class include an abstract method called Draw(Graphics g).
Within each GeometryPrimitive, include the appropriate GraphicPrimitive for drawing the object and an accessor method for accessing it. To draw the entire scene, walk your structure of GeometryPrimitive objects, asking each one for its GraphicPrimitive and then invoking the Draw() method.
abstract class GeometryPrimitive
{
public abstract GraphicsPrimitive GetGraphicsPrimitive();
}
abstract class GraphicsPrimitive
{
public abstract void Draw(Graphics g);
}
class RectangleGeometryPrimitive : GeometryPrimitive
{
public Point TopLeft {get; set;}
public Point BottomRight {get; set;}
private RectangleGraphicPrimitive gp;
public RectanglePrimitive(Point topLeft, Point bottomRight);
{
this.TopLeft = topLeft;
this.BottomRight = bottomRight;
this.gp = new RectangleGraphicsPrimitive(this);
}
public GraphicsPrimitive GetGraphicsPrimitive()
{
return gp;
}
}
class RectangleGraphicsPrimitive : GraphicsPrimitive
{
private RectangleGeometryPrimitive p;
public RectangleGraphicsPrimitive(RectangleGeometryPrimitive p)
{
this.p = p;
}
public void Draw(Graphics g)
{
g.DrawRectangle(p.TopLeft, p.BottomRight);
}
}
class CircleGeometryPrimitive : GeometryPrimitive
{
public Point Center {get; set;}
public int Radius {get; set;}
private CircleGraphicPrimitive gp;
public RectanglePrimitive(Point center, int radius);
{
this.Center = center;
this.Radius = radius;
this.gp = new CircleGraphicsPrimitive(this);
}
public GraphicsPrimitive GetGraphicsPrimitive()
{
return gp;
}
}
class CircleGraphicsPrimitive : GraphicsPrimitive
{
private CircleGeometryPrimitive p;
public CircleGraphicsPrimitive(CircleGeometryPrimitive p)
{
this.p = p;
}
public void Draw(Graphics g)
{
g.DrawCircle(p.Center, p.Radius);
}
}
As you can see above, no downcasting is required to draw GeometryPrimitives to the screen. With proper use of inheritance, you can also share GraphicsPrimitive objects between different GeometryPrimitives. For example, SquareGeometryPrimitive and RectangleGeometryPrimitive can both use RectangleGraphicsPrimitive if SquareGeometryPrimitive derives from RectangleGeometryPrimitive.

You don't give many details, so I can't really give my opinion about whether it is adequate to have the two hierarchies. We all know the costs of this parallelism, but only you can evaluate the advantages ...
I don't know your programming language. But a common solution to avoid the downcasting you mention, is to have a base class using parameterized types (called generics or templating). This works in Java, C++ and many modern languages.
The idea is that the precise type of the field base.figure is determined by each subclass. What you know in the base class is that it is a subtype T of GeometryPrimitive. In each subclass, you defined the precise type RectangleGeometric that replaces the T, so within this subclass the type is precise.
Java example:
public GraphicPrimitive<T extends GeometryPrimitive> {
protected T figure;
}
public Rectangle extends GraohicPrimitive<RectangleGeometric> {
// It appears in this class that the field was defined as
//protected RectangleGeometric figure;
public TwoDPoint getLeftTopCorner {
return new TwoDPoint(base.color, figure.LeftTopCorner);
}
}

Related

Interfaces vs. Abstract Classes or polymorphism in general

I'm having problems understanding the difference between the use of Interfaces and abstract classes.
For example, please see the following UML diagramm:
What is the difference between these two?
I'll provide an explanation with code and a shorter explanation. If you don't want to read, just skip to the "plain English explanation" below.
Explanation with code
In C++ terms an abstract class is a class which implement some methods but don't implement other methods. That means: you can use some of their methods, but you'll have to implement the non-implemented ones.
Interfaces are pure classes in C++, that is, a class which doesn't implement anything and you must implement everything if you want your class to be conformant to that interface.
E.g. - try this out with the link below
#include <iostream>
using namespace std;
// Shape is abstract class: some methods are already available, some are not
class Shape
{
public:
// This is already implemented and ready for polymorphism
virtual void area() { cout<<"Shape area"<<endl;}
// You MUST implement this
virtual void implement_me() = 0;
};
class Circle : public Shape
{
public:
virtual void area() { cout<<"Circle area"<<endl;}
void implement_me() { cout<<"I implemented it just because I had to"<<endl;}
};
class HalfCircle : public Circle
{
public:
virtual void area() { cout<<"HalfCircle area"<<endl;}
};
// ShapeInterface is a pure class or interface: everything must be implemented!
class ShapeInterface
{
public:
virtual void area() = 0;
};
class CircleFromInterface : public ShapeInterface
{
public:
// You MUST implement this!
virtual void area() { cout<<"CircleFromInterface area from interface"<<endl;};
};
int main() {
Shape* ptr_to_base = new HalfCircle();
ptr_to_base->area(); // HalfCircle area, polymorphism
ptr_to_base->Shape::area(); // Shape area
ptr_to_base->implement_me(); // from Circle
ShapeInterface *ptr_to_base_int = new CircleFromInterface();
ptr_to_base_int->area(); // Just the derived has it
return 0;
}
http://ideone.com/VJKuZx
Plain-English Explanation
If you want the over-simplified version:
Interfaces are usually "contracts" which you need to adhere in toto: you need to agree with everything and implement everything or it doesn't work.
Abstract classes are partial-contracts, there are some things which you must agree/implement, but there's also some other stuff which is already there and you can choose whether to re-implement it (override) or just be lazy and use the existing ones.
Abstract classes used for dealing with code duplication between subclasses, because they can share common logic and data. Interfaces just define common contract of implementors.
So, if there is no common implementation to share, then use interface (I always start with interface). If some common implementation will appear, then extract abstract base class and move common code there. But even in this case I keep interface in hierarchy, because it's easy to mock and it is more abstract, which allows other classes not depend on any implementation at all.
In your case I think Circle and HalfCircle share some implementation. So I would go with moving common code to Circle and inheriting HalfCircle from itŠ–
public class Circle : IShape
{
public double Radius { get; set; }
public virtual double Area
{
get { return Math.PI * Radius * Radius; }
}
}
public class HalfCircle : Circle
{
public override double Area
{
get { return base.Area / 2; }
}
}
If all shapes share some data or logic for calculating area, then it makes sense to declare base abstract Shape class for this common code. But if you will look at area calculation of square, there is nothing common with circle:
public class Square : IShape
{
public double Side { get; set; }
public double Area
{
get { return Side * Side; }
}
}
So IShape interface would be enough, because classes share only contract:
public interface IShape
{
double Area { get; }
}
An inheritance relationship, potentially using an abstract class, can usually be described as 'is a' and the implementation of an interface is a 'can be'. This concept can help when choosing which to use.
So if a Square 'is a' shape then inheritance would be an acceptable way of modelling this relationship.
Furthermore, an abstract class will give you the ability to provide common features. Where as an interface cannot contain any implementation.

design pattern query

i have a question regarding design patterns.
suppose i want to design pig killing factory
so the ways will be
1) catch pig
2)clean pig
3) kill pig
now since these pigs are supplied to me by a truck driver
now if want to design an application how should i proceed
what i have done is
public class killer{
private Pig pig ;
public void catchPig(){ //do something };
public void cleanPig(){ };
public void killPig(){};
}
now iam thing since i know that the steps will be called in catchPig--->cleanPig---->KillPig manner so i should have an abstract class containing these methods and an execute method calling all these 3 methods.
but i can not have instance of abstract class so i am confused how to implement this.
remenber i have to execute this process for all the pigs that comes in truck.
so my question is what design should i select and which design pattern is best to solve such problems .
I would suggest a different approach than what was suggested here before.
I would do something like this:
public abstract class Killer {
protected Pig pig;
protected abstract void catchPig();
protected abstract void cleanPig();
protected abstract void killPig();
public void executeKillPig {
catchPig();
cleanPig();
killPig();
}
}
Each kill will extend Killer class and will have to implement the abstract methods. The executeKillPig() is the same for every sub-class and will always be performed in the order you wanted catch->clean->kill. The abstract methods are protected because they're the inner implementation of the public executeKillPig.
This extends Avi's answer and addresses the comments.
The points of the code:
abstract base class to emphasize IS A relationships
Template pattern to ensure the steps are in the right order
Strategy Pattern - an abstract class is as much a interface (little "i") as much as a Interface (capital "I") is.
Extend the base and not use an interface.
No coupling of concrete classes. Coupling is not an issue of abstract vs interface but rather good design.
public abstract Animal {
public abstract bool Escape(){}
public abstract string SaySomething(){}
}
public Wabbit : Animal {
public override bool Escape() {//wabbit hopping frantically }
public override string SaySomething() { return #"What's Up Doc?"; }
}
public abstract class Killer {
protected Animal food;
protected abstract void Catch(){}
protected abstract void Kill(){}
protected abstract void Clean(){}
protected abstract string Lure(){}
// this method defines the process: the methods and the order of
// those calls. Exactly how to do each individual step is left up to sub classes.
// Even if you define a "PigKiller" interface we need this method
// ** in the base class ** to make sure all Killer's do it right.
// This method is the template (pattern) for subclasses.
protected void FeedTheFamily(Animal somethingTasty) {
food = somethingTasty;
Catch();
Kill();
Clean();
}
}
public class WabbitHunter : Killer {
protected override Catch() { //wabbit catching technique }
protected override Kill() { //wabbit killing technique }
protected override Clean() { //wabbit cleaning technique }
protected override Lure() { return "Come here you wascuhwy wabbit!"; }
}
// client code ********************
public class AHuntingWeWillGo {
Killer hunter;
Animal prey;
public AHuntingWeWillGo (Killer aHunter, Animal aAnimal) {
hunter = aHunter;
prey = aAnimal;
}
public void Hunt() {
if ( !prey.Escape() ) hunter.FeedTheFamily(prey)
}
}
public static void main () {
// look, ma! no coupling. Because we pass in our objects vice
// new them up inside the using classes
Killer ElmerFudd = new WabbitHunter();
Animal BugsBunny = new Wabbit();
AHuntingWeWillGo safari = new AHuntingWeWillGo( ElmerFudd, BugsBunny );
safari.Hunt();
}
The problem you are facing refer to part of OOP called polymorphism
Instead of abstract class i will be using a interface, the difference between interface an abstract class is that interface have only method descriptors, a abstract class can have also method with implementation.
public interface InterfaceOfPigKiller {
void catchPig();
void cleanPig();
void killPig();
}
In the abstract class we implement two of three available methods, because we assume that those operation are common for every future type that will inherit form our class.
public abstract class AbstractPigKiller implements InterfaceOfPigKiller{
private Ping pig;
public void catchPig() {
//the logic of catching pigs.
}
public void cleanPig() {
// the logic of pig cleaning.
}
}
Now we will create two new classes:
AnimalKiller - The person responsible for pig death.
AnimalSaver - The person responsible for pig release.
public class AnimalKiller extends AbstractPigKiller {
public void killPig() {
// The killing operation
}
}
public class AnimalSaver extends AbstractPigKiller {
public void killPing() {
// The operation that will make pig free
}
}
As we have our structure lets see how it will work.
First the method that will execute the sequence:
public void doTheRequiredOperation(InterfaceOfPigKiller killer) {
killer.catchPig();
killer.cleanPig();
killer.killPig();
}
As we see in the parameter we do not use class AnimalKiller or AnimalSever. Instead of that we have the interface. Thank to this operation we can operate on any class that implement used interface.
Example 1:
public void test() {
AnimalKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `AnimalKilleraKiller `
AnimalSaver aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
Example 2:
public void test() {
InterfaceOfPigKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `InterfaceOfPigKiller `
InterfaceOfPigKiller aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
The code example 1 and 2 are equally in scope of method doTheRequiredOperation. The difference is that in we assign once type to type and in the second we assign type to interface.
Conclusion
We can not create new object of abstract class or interface but we can assign object to interface or class type.

Interface Segregation Principle- Program to an interface

I was reading about SOLID and other design principles. I thought ISP was the same as "Program to an interface, not an implementation". But it looks like these are different principles?
Is there a difference?
Robert Martin has a very good explanation of Interface segregation principle (ISP), in his book "UML for Java Programmers". Based on that, I don't think ISP is about an interface being "focused" on one logical, coherent group of things. Because, that goes without saying; or, at least it should go without saying. Each class, interface or abstract class should be designed that way.
So, what is ISP? Let me explain it with an example. Say, you have a class A and a class B, which is the client of class A. Suppose, class A has ten methods, of which only two are used by B. Now, does B need to know about all ten methods of A? Probably not - the principle of Information hiding. The more you expose, the more you create the chance for coupling. For that reason, you may insert an interface, call it C, between the two classes (segregation). That interface will only declare the two methods that are used by B, and B will depend on that Interface, instead of directly on A.
So now,
class A {
method1()
method2()
// more methods
method10()
}
class B {
A a = new A()
}
will become
interface C {
method1()
method2()
}
class A implements C{
method1()
method2()
// more methods
method10()
}
class B {
C c = new A()
}
This, prevents B from knowing more than it should.
ISP is focused on the idea of each interface representing one discrete and cohesive behavior.
That is, each logical group of things an object should do would map to a single specific interface. A class might want to do several things, but each thing would map to a specific interface representing that behavior. The idea is each interface is very focused.
Assume that you have one fat interface with many methods to be implemented.
Any class, that implements that fat interface has to provide implementation for all these methods. Some of the methods may not be applicable to that concrete class. But still it has to provide implementation in absence of interface segregation principle.
Let's have a look at example code in absence of Interface segregation.
interface Shape{
public int getLength();
public int getWidth();
public int getRadius();
public double getArea();
}
class Rectangle implements Shape{
int length;
int width;
public Rectangle(int length, int width){
this.length = length;
this.width = width;
}
public int getLength(){
return length;
}
public int getWidth(){
return width;
}
public int getRadius(){
// Not applicable
return 0;
}
public double getArea(){
return width * length;
}
}
class Square implements Shape{
int length;
public Square(int length){
this.length = length;
}
public int getLength(){
return length;
}
public int getWidth(){
// Not applicable
return 0;
}
public int getRadius(){
// Not applicable
return 0;
}
public double getArea(){
return length * length;
}
}
class Circle implements Shape{
int radius;
public Circle(int radius){
this.radius = radius;
}
public int getLength(){
// Not applicable
return 0;
}
public int getWidth(){
// Not applicable
return 0;
}
public int getRadius(){
return radius;
}
public double getArea(){
return 3.14* radius * radius;
}
}
public class InterfaceNoSeggration{
public static void main(String args[]){
Rectangle r = new Rectangle(10,20);
Square s = new Square(15);
Circle c = new Circle(2);
System.out.println("Rectangle area:"+r.getArea());
System.out.println("Square area:"+s.getArea());
System.out.println("Circle area:"+c.getArea());
}
}
output:
java InterfaceNoSeggration
Rectangle area:200.0
Square area:225.0
Circle area:12.56
Notes:
Shape is a general purpose fat interface, which contains methods required for all Shape implementations like Rectangle, Circle and Square. But only some methods are needed in respective Shape childs
Rectangle : getLength(), getWidth(), getArea()
Square : getLength() and getArea()
Circle : getRadius() and getArea()
In absence of segregation, all Shapes have implemented entire fat interface : Shape.
We can achieve same output with interface segregation principle if we change the code as follows.
interface Length{
public int getLength();
}
interface Width{
public int getWidth();
}
interface Radius{
public int getRadius();
}
interface Area {
public double getArea();
}
class Rectangle implements Length,Width,Area{
int length;
int width;
public Rectangle(int length, int width){
this.length = length;
this.width = width;
}
public int getLength(){
return length;
}
public int getWidth(){
return width;
}
public int getRadius(){
// Not applicable
return 0;
}
public double getArea(){
return width * length;
}
}
class Square implements Length,Area{
int length;
public Square(int length){
this.length = length;
}
public int getLength(){
return length;
}
public int getWidth(){
// Not applicable
return 0;
}
public int getRadius(){
// Not applicable
return 0;
}
public double getArea(){
return length * length;
}
}
class Circle implements Radius,Area{
int radius;
public Circle(int radius){
this.radius = radius;
}
public int getLength(){
// Not applicable
return 0;
}
public int getWidth(){
// Not applicable
return 0;
}
public int getRadius(){
return radius;
}
public double getArea(){
return 3.14* radius * radius;
}
}
public class InterfaceSeggration{
public static void main(String args[]){
Rectangle r = new Rectangle(10,20);
Square s = new Square(15);
Circle c = new Circle(2);
System.out.println("Rectangle area:"+r.getArea());
System.out.println("Square area:"+s.getArea());
System.out.println("Circle area:"+c.getArea());
}
}
Notes:
Now individual Shapes like Rectangle, Square and Circle have implemented only required interfaces and got rid of un-used methods.
Agree with both the answers above. Just to give an example of TrueWill's code smell above, you shouldn't find yourself doing this:
#Override
public void foo() {
//Not used: just needed to implement interface
}
IWorker Interface:
public interface IWorker {
public void work();
public void eat();
}
Developer Class :
public class Developer implements IWorker {
#Override
public void work() {
// TODO Auto-generated method stub
System.out.println("Developer working");
}
#Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("developer eating");
}
}
Robot Class:
public class Robot implements IWorker {
#Override
public void work() {
// TODO Auto-generated method stub
System.out.println("robot is working");
}
#Override
public void eat() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("cannot eat");
}
}
For a more complete example go here.
Here's a real-world example of this principle (in PHP)
Problem Statement:
I want various forms of content to have comments/discussion associated with them. That content might be anything from a forum topic, to a news article, to a user's profile, to a conversation-style private message.
Architecture
We will want a re-usable DiscussionManager class which attaches a Discussion to a given content entity. However, the above four examples (and many more) are all conceptually different. If we want the DiscussionManager to use them, then all four+ need to have one common interface that they all share. There is no other way for DiscussionManager to use them unless you want to your arguments to go naked (e.g. no type checking).
Solution: Discussable interface with these methods:
attachDiscussion($topic_id)
detachDiscussion()
getDiscussionID()
Then DiscussionManager might look like this:
class DiscussionManager
{
public function addDiscussionToContent(Discussable $Content)
{
$Discussion = $this->DiscussionFactory->make( ...some data...);
$Discussion->save() // Or $this->DiscussionRepository->save($Discussion);
$Content->attachDiscussion($Discussion->getID()); // Maybe saves itself, or you can save through a repository
}
public function deleteDiscussion(Discussable $Content)
{
$id = $Content->getDiscussionID();
$Content->detatchDiscussion();
$this->DiscussionRepository->delete($id);
}
public function closeDiscussion($discussion_id) { ... }
}
This way, DiscussionManager does not care about any of the unrelated behaviors of the various content types that it uses. It ONLY cares about the behaviors it needs, regardless of what those behaviors are associated with. So by giving each content type that you want to have discussions for, a Discussable interface, you are using the interface segregation principle.
This is also a good example of a situation where an abstract base class is not a good idea. A forum topic, user profile, and news article aren't even remotely conceptually the same thing, thus trying to get them to inherit the discussion behaviors leads to strange coupling to an unrelated parent. Using a specific interface that represents discussions, you can makes sure that the entities you want to have discussions, are compatible with the client code that will be managing those discussions.
This example might also be a good candidate for usage of Traits in PHP, for what it's worth.

Refactoring Switching On Types Code Smell When Adding Method to Type Seems Inappropriate

Let's say I have the following method that, given a PaymentType, sends an appropriate payment request to each facility from which the payment needs to be withdrawn:
public void SendRequestToPaymentFacility(PaymentType payment) {
if(payment is CreditCard) {
SendRequestToCreditCardProcessingCenter();
} else if(payment is BankAccount) {
SendRequestToBank();
} else if(payment is PawnTicket) {
SendRequestToPawnShop();
}
}
Obviously this is a code smell, but when looking for an appropriate refactoring, the only examples I have seen involve cases where the code executed within the conditionals are clearly the responsibility of the class itself, e.g. with the standard example given:
public double GetArea(Shape shape) {
if(shape is Circle) {
Circle circle = shape As Circle;
return circle.PI * (circle.radius * circle.radius);
} else if(shape is Square) {
Square square = shape as Square;
return square.length * square.width;
}
}
GetArea() seems like a pretty reasonable responsibility for each Shape subclass, and can of course be refactored nicely:
public class Shape
{
/* ... */
public abstract double GetArea();
}
public class Circle
{
public override double GetArea()
{
return PI * (radius * radius);
}
}
However, SendRequestToPaymentFacility() does not seem like an appropriate responsibility for a PaymentType to have. (and would seem to violate the Single Responsibility Principle). And yet I need to send a request to an appropriate PaymentFacility based on the type of PaymentType - what is the best way to do this?
You could consider adding a property or method to your CandyBar class which indicates whether or not the CandyBar contains nuts. Now your GetProcessingPlant() method does not have to have knowledge of the different types of CandyBars.
public ProcessingPlant GetProcessingPlant(CandyBar candyBar) {
if(candyBar.ContainsNuts) {
return new NutProcessingPlant();
} else {
return new RegularProcessingPlant();
}
}
One option would be to add an IPaymentFacility interface parameter to the constructors for the individual PaymentType descendants. The base PaymentType could have an abstract PaymentFacility property; SendRequestToPaymentFacility on the base type would delegate:
public abstract class PaymentType
{
protected abstract IPaymentFacility PaymentFacility { get; }
public void SendRequestToPaymentFacility()
{
PaymentFacility.Process(this);
}
}
public interface IPaymentFacility
{
void Process(PaymentType paymentType);
}
public class BankAccount : PaymentType
{
public BankAccount(IPaymentFacility paymentFacility)
{
_paymentFacility = paymentFacility;
}
protected override IPaymentFacility PaymentFacility
{
get { return _paymentFacility; }
}
private readonly IPaymentFacility _paymentFacility;
}
Rather than wiring up the dependency injection manually, you could use a DI/IoC Container library. Configure it so that a BankAccount got a Bank, etc.
The downside is that the payment facilities would only have access to the public (or possibly internal) members of the base-class PaymentType.
Edit:
You can actually get at the descendant class members by using generics. Either make SendRequestToPaymentFacility abstract (getting rid of the abstract property), or get fancy:
public abstract class PaymentType<TPaymentType>
where TPaymentType : PaymentType<TPaymentType>
{
protected abstract IPaymentFacility<TPaymentType> PaymentFacility { get; }
public void SendRequestToPaymentFacility()
{
PaymentFacility.Process((TPaymentType) this);
}
}
public class BankAccount : PaymentType<BankAccount>
{
public BankAccount(IPaymentFacility<BankAccount> paymentFacility)
{
_paymentFacility = paymentFacility;
}
protected override IPaymentFacility<BankAccount> PaymentFacility
{
get { return _paymentFacility; }
}
private readonly IPaymentFacility<BankAccount> _paymentFacility;
}
public interface IPaymentFacility<TPaymentType>
where TPaymentType : PaymentType<TPaymentType>
{
void Process(TPaymentType paymentType);
}
public class Bank : IPaymentFacility<BankAccount>
{
public void Process(BankAccount paymentType)
{
}
}
The downside here is coupling the Bank to the BankAccount class.
Also, Eric Lippert discourages this, and he makes some excellent points.
One approach you can take here is to use the Command pattern. In this case, you would create and queue up the appropriate command (e.g. Credit Card, Bank Account, Pawn Ticket) rather than calling a particular method. Then you could have separate command processors for each command that would take the appropriate action.
If you don't want the conditional complexity here, you could raise a single type of command that included the payment type as a property, and then a command processor could be responsible for figuring out how to handle that request (with the appropriate payment processor).
Either of these could help your class follow Single Responsibility Principle by moving details of payment processing out of it.

Design pattern to save/load an object in various format

I have an object: X, that can be saved or loaded in various formats: TXT, PDF, HTML, etc..
What is the best way to manage this situation? Add a pair of method to X for each format, create a new Class for each format, or exists (as I trust) a better solution?
I'd choose the strategy pattern. For example:
interface XStartegy {
X load();
void save(X x);
}
class TxtStrategy implements XStartegy {
//...implementation...
}
class PdfStrategy implements XStartegy {
//...implementation...
}
class HtmlStrategy implements XStartegy {
//...implementation...
}
class XContext {
private XStartegy strategy;
public XContext(XStartegy strategy) {
this.strategy = strategy;
}
public X load() {
return strategy.load();
}
public void save(X x) {
strategy.save(x);
}
}
I agree with #DarthVader , though in Java you'd better write
public class XDocument implements IDocument { ...
You could also use an abstract class, if much behavior is common to the documents, and in the common methods of base class call an abstract save(), which is only implemented in the subclasses.
I would go with Factory pattern. It looks like you can use inheritance/polymorphism with generics. You can even do dependency injection if you go with the similar design as follows.
public interface IDocument
{
void Save();
}
public class Document : IDocument
{
}
public class PdfDocument: IDocument
{
public void Save(){//...}
}
public class TxtDocument: IDocument
{
public void Save(){//...}
}
public class HtmlDocument : IDocument
{
public void Save(){//...}
}
then in another class you can do this:
public void SaveDocument(T document) where T : IDocument
{
document.save();
}
It depends on your objects, but it is possible, that visitor pattern (http://en.wikipedia.org/wiki/Visitor_pattern) can be used here.
There are different visitors (PDFVisitor, HHTMLVisitor etc) that knows how to serialize parts of your objects that they visit.
I would instead suggest the Strategy pattern. You're always saving and restoring, the only difference is how you do it (your strategy). So you have save() and restore() methods that defer to various FormatStrategy objects you can plug and play with at run time.