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".
Related
My design problem is as follows.
I have two classes, each with a number of subclasses. I have a factory, which needs to create an object based on the subclass of each of these objects.
This is an authentication problem. The factory generates a rule object based on the type of person and the type of resource they wish to access. The rule has alwaysAllow, NeverAllow and timeBasedAllow subclasses. With the potential for more if a more complex access system is needed in the future.
So in future ideally a new person could be created with a new subclass, a new resource with a new subclass. The parameters on which access is determined could be changed with a new rule subclass, and the specific access of each person type and room type could be changed within the rule factory.
So far the only way I can think to do this would be to have an enumeration inside the subclasses, which defeats the point because then adding a new person or room requires a new class and a change in the enum class which seems messy.
I also am very keen to keep the data and the logic separate so I can’t just move authentication methods into the person class because this would require the person class to know how many room types there were, which is definitely not ideal.
I may be after something that isn’t realistically achievable but I can’t help the feeling that there is a nice clean solution just out of my grasp.
Any help would be greatly appreciated.
Your question title makes it sound as if you are searching for multiple-inheiritance, which is not allowed in Java. Unlike in C++, a class may extend one and only one class. However, Java also has interface, which I suspect may be what you seek.
An interface class cannot be instantiated, and may have abstract methods. A
concrete class may implement as many interfaces as desired, and the concrete class must implement each abstract method the interface declares. Abstract classes may also implement interfaces, and abstract methods they do not implement must be implemented by concrete classes extending them.
I suggest extracting your authentication methods into aninterface, perhaps called AuthRule or somesuch. AuthRule can have abstract methods with represent authenticating, without exposing the exact style used to authenticate. So, you would implement AlwaysAllow implements AuthRule and then the authenticate methods on AlwaysAllow would always return true.
The second thing, however, is that you appear to be attempting to use inheritance when composition would better suit your needs. Now instread of having a Person inherit his authentication-rule, the rule should instead be a member field inside Person. So, for example:
class Person extends User {
AuthRule rule;
Person(AuthRule myrule) {
rule = myrule;
}
bool authenticate(...) {
return rule.authenticate(...);
}
}
If you follow a design pattern based on injecting objects into other objects to mix in the functionality you desire, your code will become far more usable and extensible. I hope this helps your problem.
For example : http://www.tutorialspoint.com/design_pattern/factory_pattern.htm
If I change interface shape on abstract class Shape, make concrete classes to extend Shape and Make the Shape factory return Shape abstract class typed objects. Is it still going to be a factory pattern ?
I would go with yes.
Lets look at definition of Factory method pattern:
the factory method pattern is a creational pattern which uses factory methods to deal with the problem of creating objects without specifying the exact class of object that will be created
The motivation behind this pattern is to separate object creation from the client using the object. Client should provide specification to factory but details how the object is built are abstracted away by the factory.
If this is an interface or abstract class is an implementation detail specific to situation, as long as your implementation of the factory lets you achieve the motivation behind pattern.
Consider using abstract classes if any of these statements apply to your situation:
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
Consider using interfaces if any of these statements apply to your situation:
You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
You want to take advantage of multiple inheritance of type.
In some implementations it might even make more sense to use abstract class rather then interface for the Products created by the factory. If there is shared set of features/behavior between all products then it does make sense to put these into base abstract class. This could apply even if products are built from different factories.
It boils down to: do you wish to and does it make sense to introduce coupling
between products or not?
In the end, client will get same result - Product built based upon specification, with details of construction abstracted away.
When it comes to these kind of differences, the answer can always be both yes and no. Design patterns are not any kind of precise specification, they are more like a set of best and recommended practices and their implementation varies from case to case.
In my opinion the answer is no, technically this would not be a factory pattern. And it does not have to be, as long as it solves your use case and makes the code readable and maintainable (trying to literally adhere to design patterns often leads to misusing them and to over-architecturing).
If we look at the Abstract Factory Pattern (right below the Factory Pattern in the linked page), we'll see that it is a factory for creating factories. Now suppose that we have two Shape factories that can be created by the AbstractFactory: ShapeFactory2D and ShapeFactory3D, both producing Shape objects.
If Shape were abstract class, then you would force both 2D and 3D objects to inherit the same implementation, although it might make no sense (they could be implemented in totally different ways).
So, technically, in order for this to really be a factory pattern, there must exist no assumptions about the implementation details, meaning abstract classes containing partial implementation should not be used at the factory interface level.
Of course you can have Abstract2DShape and Abstract3DShape abstract classes implementing Shape; the point is that you are able to create and use Shape without being aware whether it is a 2D or a 3D shape.
I'm currently making an easy webshop application. The webshop is required to add three kinds of objects to the shoping cart. A CD, a Book or a Game. I made a class for every object which all have a toString() method.
Now I have to make a method add(..) which needs to add the specified object to an ArrayList called shoppingcart. This method needs to be called within the class Webshop which in itself has the objects that are created.
I know how to do this with multiple add methods but it's required to do it with a single method.
You will probably want to create a new type called something like AbstractItem and all your other types extend from this. It is also a good practice to hide this abstract class behind an interface. So, the AbstraxtItem class could implement an Item interface that would define the public APIs.
The AbstractItem class would define some abstract methods that its subtypes should implement like getPrice() and possibly other concrete methods that would be the common behavior for all subclasses. The shopping cart will be an ArrayList<Item> and that would be populated by the add(Item) method.
Each object in your shop which can be add should implement an interface IProduct.
You then have a list of IProduct, which you can add.
ArrayList<IProduct> shoppingBasket = new ArrayList<IProduct>();
You could let the classes CD, Book and Game implement an Interface, e.g. ShopObject.
Then you can have your shoppinCart like this:
ArrayList<ShopObject> shoppingCart = new ArrayList<ShopObject>();
OOP can help you solve this problem :
If you find CD, Book or Game has some common attribute then you can use a Base class with common features and let all these extend that class.
So CD, Book and Game extends a class say Product and you provide a generic add method which takes Product as parameter.
add(Product product);
If CD, Book and Game don't share any common features then also you can use OOPs feature to add all these in more simpler way; but here you need to use method overloading
add(CD cd);
add(Book book);
So will suggest, think over your application design and then take a call on either of the approaches.
You can use aggregate all objects in one using a discriminant to indicate which object is really being represented pretty much like variant records in Ada or unions in C.
You have a full example here: http://lambda-the-ultimate.org/node/2694#comment-40453
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.
Assume, we have an abstract class A and we want to force all subclasses to have a certain field. This is not possible in Java, because we can not define abstract fields.
Workaround 1: Force subclasses to implement a method which delivers the wanted value.
abstract class A {
abstract int getA();
}
Drawback: Each subclass has to implement a method for each abstract field we want to have. This can lead to many method implementations.
Advantage: We can use the method getA in the abstract class and implement methods with it in A without implementing them in each subclass. But the value behind the method can not be overwritten by the abstract class.
Workaround 2: Simulate the abstract field by forcing the subclass to give the abstract class a value.
abstract class A {
int a;
public A(int a) {
this.a = a;
}
}
Drawback: When we have multiple fields (> 10), the super constructor call will look a bit ugly and confusing.
Advantage: We can use the field a in the abstract class and implement methods with it in A without implementing them in each subclass. Plus, the value a can be overwritten by the abstract class.
Question: Which workaround is the common way to reach the goal ? Maybe there is a better one than the above ones ?
The abstract method is probably the most object oriented.
If you have too many fields, you may want to regroup those in a POJO (if a new concept is appropriate).
I prefer the first one . i dont love to couple classes in fileds name , how they handle state and how they save it. the first one is more close to open/close principal
I recommend to avoid inheritance. inheritance is very frigle and hard to maintenance. remember effective java advice - prefer composition other inheritance
I think opt.1 is the cleaner by far. A few getters and setters is not a big deal, and I doubt that many use cases would have more than just a few abstract "fields".
About opt.2, you forget that constructors are not inherited, and thus would require all sub classes constructors to be implemented in a way that takes a into account.
Workaround 2 is very common because of 2 advantages:
1) the one you mentioned - the field does not belong to the subclass - it belongs to the parent and that is important because it was "demanded" by the parent and because the parent can use it
2) When sub-classing from the parent you are very aware of this field because when you implement the constructor you must pass it on. If I saw the first workaround I wouldn't know what to understand from it, in this way I understand that the parent class needs this field to work, so it must have a meaningful value.
note: if you have a class that has 10 fields that need to be initialized something is probably wrong in your design.
1. Actually its not about what one prefers but its about the flexibility, and the ability
to adapt changes.
2. Its always better to Encapsulate Behaviors that keeps changing, either into an Interface or Abstract class.
3. You 1st Workaround will be good in places where you need different implementation for the same Behavior in Different classes. Then at this place either an Interface or your 1st Workaround will be a good choice.
Eg:
Consider Painting as a Class with paint() Method.
Now
paint() method can have Stroking, gliding, shading etc styles of doing it.
Then its better to Encapsulate that method into an Abstract class or an Interface.
public interface Paint{
paintDoIt(String style);
}
4. Your 2nd Wordaround will be good in a place, where you want certain behaviors to be MUST implemented by the Subclass.
Eg:
Consider Car as an Abstract Class, Now to be car its very important that it must have
a Steering, 4 wheels, Engine, etc. So these features must be implemented.
where as other features like music system, LCD ,etc are optional and depends on the car type.