Design Pattern - Class with general and specialized properties - java

I am trying to see if there is a design pattern that can solve this:
I have created an abstract class A with properties a,b and c. I have another class B that extends the class A and adds more properties: x,y,z. Then I have another class C that again extends A and adds i,j,k. Lastly I have a factory method that determines which instance to create B or C and thats the part where I need help. How or what should this factory method return: If it returns an instance of A than I wouldnt know which specific instance was created B or C? I need this factory method to create a concrete instance. Now, I know that I could write static method like createB or createC but I am looking for a more general solution maybe another design pattern here.
Update: The reason I want to know the concrete class is that I need to pass this object to a frontend jsp. That JSP would need to know what specific class was instantiated so it can call the appropriate getters.

I would Keep Factory Pattern as it should. so the return type would be the Abstract A class. B & C Should also inherit their properties through Proxy Pattern.
So Make CAble & BAble Interfaces and use C & B as instances of A (as they're both generated by the same factory), then cast B & C to act as their Interfaces Describe.
Cheers!
UPDATE:
I think I've figured what you need, picture the following:
In a School Page.
There is a general view of Students & Professors, both have common and individual fields, but the common request is schoolMember.
class SchoolMember // The return type of your Factory
-name
+getView():SchoolMemberView // Will be used by the View//View Model
Interface Professor
getProfession()
Interface Student
getSemester()
class FacultyMamber: SchoolMember,Professor
-profession
+getView():SchoolMemberView
class UniStudent: SchoolMember,Student
-semmester
+getView():SchoolMemberView

By the sound of your description both B and C have nothing in common with A. You've mentioned that each class has particular properties but nothing about what they have in common / how they are related. If there is no relationship between your classes you shouldn't be using inheritence.
However, if there is a common relationship which you have not mentioned in your question, the factory method pattern would probably be what you're looking for.

The only thing that comes to mind when reading your problem is the abstract factory pattern:
http://en.wikipedia.org/wiki/Abstract_factory_pattern

Factory method should return an instance of A. If you need to know if concrete object is B or C, you can use instanceof operator, which is Reflection pattern. Ideally, you shouldn't need to know if you have B or C; that logic should all be handled by polymorphism of methods in A.

Exactly the point mentioned as a warning in the description of Factory pattern.
When you design an application just think if you really need it a factory to create objects. Maybe using it will bring unnecessary complexity in your application. Anyway if you have many object of the same base type and you manipulate them mostly as abstract objects, then you need a factory. I you're code should have a lot of code like the following, reconsider it.
if (genericProduct typeof ConcreteProduct)
((ConcreteProduct)genericProduct).doSomeConcreteOperation();
Source : http://www.oodesign.com/factory-method-pattern.html

I would suggest a Builder pattern that will know what object to build based on the specialized field set to the Builder.

Related

Is it wise to create a pojo which inherit from a class and has dependency(object) of the same class?

I saw someone writing a POJO class similar to as below:
class A{
someVariables...
}
class B extends A{
A a = new A();
someVariables...
}
I am pretty convinced that this is not a wise way to create a class because it will cause the data integrity problem(both variable inherited and of object 'A' can have different values) when both variables are intended to store same value. Each time if someone updates any variable he has to update it at two places. I would appreciate is someone can enlighten me on this and tell me where it can be wise to create such class...Pros and cons will work.
It would be better to provide complete class code. But I think it's the decorator design pattern. Decorator design pattern is extensively used in most Java IO classes and it's a kind of modifying functionality at runtime for objects.
For more information about it, check the page Decorator Design Pattern in Java Example

Java inheritance, two-step inheritance

I have the main abstract class that is a base for bunch of classes. Some of them does not need all the fields and methods from the main abstract class, so I have created second abstract class and splitted main abstract class into two parts. The main abstract class contains, for example, a, x fields and their getters/setters, the second abstract class inherits from the main and contains additional b, c fields and their getter/setters. There are simple classes that are inheriting from the main class,and more complicated are inheriting from the second class. I want to create objects of each class as instances of the main class. Is it right way to do that? I have to type check and cast when I want to use methods from the second abstract class. It makes my code complicated. How can I solve this problem?
MainAbstractClass ---> SecondAbstractClass ---> MyComplicatedClasses
|
|
V
MySimpleClasses
One of the OO principles is Favor composition over inheritance.
This means that common behavior is not provided through base classes but via Component classes which are passed in via dependency injection (preferably as constructor parameters.
The answer depends on your actual needs.
You can instead choose to store the extended abstract class specific fields in a class that does not implement your base class and make it a member of more complicated classes.
You can choose to keep everything in a single base class and nothing forces you to use all the fields of an interface in every class that implemented your interface.
You can also keep using your approach but since you store the classes as an instance of the base class, it will be hard to read.
I believe that if you think code does not look very good, it is probably not good. However, there is usually no single answer to this kind of design questions and the best solution is relative to your preferences.
I think this need of type cast is a smell of fragile design. Here when we assume MyComplicatedClass ISA KIND OF MainAbstractClass as shown by TJ Crowder then object must behave as MainAbstractClass (meaning it can honor only API of MainAbstractClass). If it expects special treatment as MyComplicatedClass its false commitment and will need Casting. Such casting (by identifying type) goes against OO principles and kills polymorphism. Later this will end up in Ladder of InstanceOf and type casts as in the scenarios rightly pointed out by T.J. Crowder.
I would suggest readdress the design. e.g. though our all user defined type instances ARE KIND OF Object, but we use Object API only for methods defined in Object class. We do not use Object o = new MyClass(). There are occasions in frameworks or like Object.equals() method where type cast is needed as API is defined before even concrete extension is written. But it is not a good idea for such simple complete (without open hooks for extensions) Hierarchies.

How to dynamically process the java object?

If we have a parent class Vehicle and its child classes as Bus, BiCycle, MotorBike.
At a certain point of time in a service class, I will be getting all the objects like List vehicles.
My Business logic should be like below,
A list of faulty vehicles will be received and for each vehicle type, a respective mechanic should be allocated.
If I receive a bicycle it should go to a bicycle mechanic or other vehicle and their respective mechanics.
It looked bad when I used to switch case and if else conditions.So I tried to use the Visitor pattern and Factory pattern, Factory pattern also will use either switch or if-else conditions to get the object dynamically and call the overridden method. Currently using the visitor pattern.
Kindly suggest some approach which would work better with this case.
Define a sendToMechanic abstract method in Vehicle class and override it with the appropriate definition in each of the child classes.
I would suggest all three subclasses to implement the same interface (e.g. repairable) with a method like `allocateToMechanic. An interface is mostly describing "what an object can do" vs the abstract class which describes "what an object is".

AbstractClass.getInstance() method is this an anti-pattern

In some places where a class hierarchy is present and the top most base class is an abstract class there is a static getInstance() method in the abstract class. This will be responsible for creating the correct sub-class and returning it to the caller. For example consider the below code.
public class abstract Product {
public static Product getInstance(String aCode) {
if ("a".equals(aCode) {
return new ProductA();
}
return ProductDefault();
}
// product behaviour methods
}
public class ProductA extends Product {}
public class ProductDefault extends Product {}
In Java, java.util.Calendar.getInstance() is one place this pattern has been followed. However this means each time a new subclass is introduced one has to modify the base class. i.e: Product class has to be modified in the above example. This seems to violate the ocp principle. Also the base class is aware about the sub class details which is again questionable.
My question is...
is the above pattern an anti-pattern ?
what are the draw-backs of using the above pattern ?
what alternatives can be followed instead ?
The interface is not an anti-pattern. But the way you've implemented it is rather poor ... for the reason you identified. A better idea would be to have some mechanism for registering factory objects for each code:
The Java class libraries do this kind of thing using SPIs and code that looks reflectively for "provider" classes to be dynamically loaded.
A simpler approach is to have a "registry" object, and populate it using dependency injection, or static initializers in the factory object classes, or a startup method that reads class names from a properties file, etcetera.
No it's not. It's more like factory method pattern http://en.wikipedia.org/wiki/Factory_method_pattern. E.g. Calendar.getInstance();. JDK is full of such examples. Also reminds of Effective Java Item 1: Consider static factory methods instead of constructors
There are a number of separate issues here.
getInstance is probably going to be a bad name. You explicitly want a new object you can play around with. "Create", "make", "new" or just leave that word out. "Instance" is also a pretty vacuous word in this context. If there is sufficient context from the class name leave it out, otherwise say what it is even if that is just a type name. If the method returns an immutable object, of is the convention (valueOf in olden times).
Putting it in an abstract base class (or in an interface if that were possible) is, as identified, not the best idea. In some cases an enumeration of all possible subtypes is appropriate - an enum obviously and really not that bad if you are going to use visitors anyway. Better to put it in a new file.
Anything to do with mutable statics is wrong. Whether it is reusing the same mutable instance, registration or doing something disgusting with the current thread. Don't do it or depend (direct or indirectly) on anything that does.
Based on the feedback i introduced a new ProductFactory class that took care of creating the correct Product. In my case the creation of the correct product instance depends on an external context (i've put the product code for the purpose of simplicity.. in the actual case it might be based on several parameters.. these could change over time). So having a Product.getInstance() method is not that suited because of the reasons outlined in the question. Also having a different ProductFactory means in the future.. Product class can become an interface if required. It just gives more extensibility.
I think when the creation of the object doesn't depend on an external context.. like in the case of Calendar.getInstance() it's perfectly ok to have such a method. In these situations the logic of finding the correct instance is internal to that particular module/class and doesn't depend on any externally provided information..

how do you use the objects from a class if you change it to an abstract class and extend it in another class?

I want to turn a class I made into an abstract class and get another class to extend it. This is because the class (particle) is leaning heavily on the class I want to make abstract (vector).
I am not sure how I will use all those objects I instantiated with the new keyword or if it will totally mess things up. I am willing to try it to learn something about using the abstract classes in my own example but if anyone can help me understand what I am doing that would be great!
if your new class depends on vector then rather than inheriting it try composition ...
so lets say u want to make ur own Queue then its not good idea to inherit from vector rather have a data member of type vector .
this has many advantage over inheritance . If u need to change the container to some other say set u do not have to worry about changing interface. You still will have some add and remove interface to your class. So client code will be independent of the container you are using to generate Queue.
Just on side notes : Consider using composition over inheritance. And look at some design patterns and try understanding when you need composition and when u can not avoid inheritance.
from wht I understand you are trying to convert class MyClass to abstract class AbstractMyClass
So, If you convert MyClass to an abstract class all the statements like
AbstractMyClass myClass=new AbstractMyClass();
will give you an error as you cannot make an instance of an AbstractMyClass.
Also, if the situation is
abstract class AbstractMyClass
{
}
class ConcreteMyClass extends AbstractMyClass
{
}
then do can do something like
AbstractMyClass abstractMyClass=new ConcreteMyClass();
or the usual
ConcreteMyClass concreteMyClass=new ConcreteMyCLass();
Inheritance : is a relation. More importantly the interface of base class and sub class should be same. Here u do not want client code to add new element using push_back()(for C++) but a mothod like add().So interface is different, a clear indication of wrong use of inheritance.Composition : has a and also "implemented in terms of". This is from Scott Mayer in effective C++. As with your case, u want implement a new DataStrucutre in terms of some thing. So composition is what you need. Now derived class does not need to have same interface. In general if you find interface to be same its more like inheritance and if not composition. There are tons of other advantage of compositon on inheritance. Just google or pick any good design book.

Categories

Resources