Explanation of Java Factory Design Pattern or Factory Class - java

I am going through HackerRank and had a quick question regarding the Factory Design Pattern or Factory Class. I am going through a basic challenge (https://www.hackerrank.com/challenges/java-factory/problem) and was able to solve it (code shown below). I wrote the portion of the code that is indicated by the comments below, while the rest was provided.
import java.util.*;
import java.security.*;
interface Food {
public String getType();
}
class Pizza implements Food {
public String getType() {
return "Someone ordered a Fast Food!";
}
}
//I implemented the part starting here
class Cake implements Food {
public String getType() {
return "Someone ordered a Dessert!";
}
}
class FoodFactory {
public Food getFood(String order) {
if (order.equalsIgnoreCase("Pizza")){
return new Pizza();}
else return new Cake();
}//End of getFood method; this is the end of the part I implemented
}//End of factory class
public class Solution {
public static void main(String args[]){
Do_Not_Terminate.forbidExit();
try{
Scanner sc=new Scanner(System.in);
//creating the factory
FoodFactory foodFactory = new FoodFactory();
//factory instantiates an object
Food food = foodFactory.getFood(sc.nextLine());
System.out.println("The factory returned "+food.getClass());
System.out.println(food.getType());
}
catch (Do_Not_Terminate.ExitTrappedException e) {
System.out.println("Unsuccessful Termination!!");
}
}
}
I have spent quite a bit of time reading through several examples online of the Factory Design Pattern, but it isn't exactly clear to me what is the purpose of the Factory Pattern and why it is beneficial or what it is simplifying/what problem it is solving. Similarly, trying this actual example hasn't quite elucidated the issue to me.
Can someone explain this in a very basic way and similarly, what would be alternatives to using the Factory Pattern? Perhaps this code that was provided in this exercise oversimplified the issue and this is why I am not clear on what the Factory accomplished. Thank you for some help as some real world color would help greatly. I have read about various design patterns and know what they are but I don't understand the issue well enough having limited real world experience with them

The basic idea of a factory is 2 things:
Obfuscate to the user (the developer) how objects are created
Put all object creation through a single place of origin.
Why do you need the factory in the first place?
Well the easiest answer is so that you could control the object creation.
Let's take a real world example:
You want to write an analytics for your app.
You happily write a class that implements some library for analytics that you use.
And go over all of your app and write AnalyticsEventManager().sendEvent(blabla)
What is the problem with this?
There came a day you want to add another analytic or replace the
current one
How do you check that all the places you need the analytic it is actually invoked?
Well factory to the rescue.
instead of AnalyticsEventManager().sendEvent(blabla)
You write an interface that has a "sendEvent" method
interface AnalyticEventSender {
void sendEvent(String eventData);
}
Then you have a few instances of different classes that implement this analytic
class FacebookAnalytic implements AnalyticEventSender {
#Override
public void sendEvent(String eventData){
System.out.println("I am facebook analytics sender:" + eventData);
}
}
Then you have
class TestAnalytic implements AnalyticEventSender {
#Override
public void sendEvent(String eventData){
System.out.println("I am test analytics sender:"+eventData);
}
}
Then you have analytic factory
class AnalyticFactory {
public static AnalyticEventSender create(){
if(allowFacebookAnalytic){
return new FacebookAnalytic();
}else {
return new TestAnalytic();
}
}
}
and so just like that you were able to replace ALL the instances of your analytic based on some boolean (the reason for changing the analytic is up to the discretion of the one who wrote the code)
And now instead of doing AnalyticEventManager().sendEvent you would write AnalyticFactory.create().sendEvent(blabla)
So now, If you want to check that your events are actually printed the way you want them to be printed, you just replace the instance that is returned in the factory with the TestAnalytic and check that the events are printed, without actually going through the real facebook module.
This is true for many other applications, not just analytics.

I suggest you read Effective Java, 3rd Edition, by Joshua Bloch, Item 1. You can look it up in Google, but one of the links is Effective Java, 3rd Edition.

Related

Converting Sequence Diagram to Java code

My teacher assigned an exercise which consists in translating (in the best possible way) a sequence diagram to Java code.
This is the sequence diagram:
And this is my attempt at solving this:
import java.util.ArrayList;
import java.util.List;
class Seminar {
private int getMark() {
return calculateMark();
}
private int calculateMark() {
return 10;
}
}
class Student {
private List<Seminar> _seminars = new ArrayList<>();
public List<Seminar> getSeminars() {
return _seminars;
}
}
class TranscriptBuilder {
public void New(Student student) {
}
}
But I couldn't finish TranscriptBuilder as I couldn't find anything about <<system>> and what it means. Any suggestions, please?
The <<system>> is a sterotype in UML :
A stereotype defines how an existing metaclass may be extended, and enables the use of platform or domain specific terminology or notation in place of, or in addition to, the ones used for the extended metaclass.
I think here it refers to the core system where you need to implement a method to print the Student information.
I suggest you #Override the toString() method in Student then implement a print() method in SharedServices as indicated in your diagram.
You are missing the guts of the TranscriptBuilder constructor, particularly, getting the seminars and doing the loop as in the diagram.
TranscriptBuilder(Student s) {
List<Seminar> sems = s.getSeminars();
for (Seminar sem : sems)
sem.getMark();
}
Your 'system' is an Actor stereotyped 'system'.
All actors are external to your system definition. They are humans or other software systems interacting with your software.
You will not implement the printer, you will only use its API to print the result.

Simple factory and Factory Method Design pattern difference

I am learning design patterns newly & I am trying to understand the difference between Simple Factory & Factory Method Pattern. First I want to clear that , I tried reading lot of articles from Stack-overflow and other sites regarding the same but that doesn't helped me.
Here is my question:
Lets consider I have a product hierarchy as shown below:
I have written a simple Factory class as shown below
public class SimpleItemFactory {
static Item getItem(String type) {
if(type.equals("Cake")) {
return new Cake();
}else if(type.equals("Chocolate")) {
return new Chocolate();
}else {
return null;
}
}
}
so now I have all the object creation in one place , so if tomorrow any changes occurs[Like constructor needs one parameter] we need to change in only one place. But it breaks OPEN CLOSED principle as if tomorrow we add more item we need to change getItem() methods if condition. So we go for Factory Method Pattern
We create Factory class as shown below:
public abstract class ItemFactory {
abstract Item getItem();
}
class CakeFactory extends ItemFactory {
#Override
Item getItem() {
return new Cake();
}
}
class ChocolateFactory extends ItemFactory {
#Override
Item getItem() {
return new Chocolate();
}
}
class Client{
public static void main(String[] args) {
Item chocolate = new ChocolateFactory().getItem();
System.out.println(chocolate);
}
}
Now when the client want to add new Item called IceCream, they just create new Factory called IceCreamFactory and create IceCream from that as shown below:
class IceCreamFactory extends ItemFactory{
#Override
Item getItem() {
return new IceCream();
}
}
class Client{
public static void main(String[] args) {
Item iceCream = new IceCreamFactory().getItem();
System.out.println(iceCream);
}
}
Is my understanding correct?
We satisfied Open closed principle here, but for each product(Item) we need one Factory class, does not it become manageable nightmare?
NOTE: Article I was referring https://www.codeproject.com/Articles/1135918/Factory-Patterns-Factory-Method-Pattern?msg=5380215#xx5380215xx
Your understanding actually is correct, just you need to note that every design pattern is made to solve at least one single issue, sometimes it could bring with it some other complexities or side effects, which means there is no perfect design pattern that could solve every problems.
For learning purposes you apply design patterns one by one (that makes the real power of design patterns sames to be shy or hiding), however in a real world context design patterns are mixed together (or even you can invent a new one :p) for the purpose of creating something that satisfy most your needs and becomes near to ideal, you can meet for example the Builder pattern mixed with Factory pattern or Factory pattern with Strategy pattern, or even the three of them mixed together...
For your case here I propose for example to use Factory Method Pattern together with Simple Factory Pattern combined with Dependency Injection Pattern to create something totally beautiful and at the same time satisfying the Open closed principal.
class ItemFactoryContainer() {
private Map<String, ItemFactory> factories = new HashMap<>();
public void register(String name, ItemFactory factory) {
factories.put(name, factory);
}
public ItemFactory getFactory(String name) {
return factories.get(name);
}
}
public class ItemFactoryTest {
public static void main(String...args) {
ItemFactoryContainer factoryContainer = new ItemFactoryContainer();
factoryContainer.register("choclate", new ChocolateFactory ());
factoryContainer.register("cake", new CakeFactory ());
factoryContainer.register("iceCream", new IceCreamFactory ());
Chocolate choclate = factoryContainer.getFactory("choclate").getItem();
Cake cake = factoryContainer.getFactory("cake").getItem();
}
}
Answers (by #Mouad EL Fakir and #François LEPORCQ) are about the static factory. That is your first part of the code.
There are two more flavors namely Factory Method and Abstract Factory)
Second part of your code is using CakeFactory and ChocolateFactory, you are trying to use Factory Method (though your naming suggests Abstract Factory). The usage of factory method getXXX() here is incorrect. The purpose of these patterns is different. In your code you are not achieving anything but increasing number of classes. (though increased number of classes and parallel hierarchies is documented as cost associated with Factories)
I have answered a similar questions recently see if those answers are helpful
Role of Creator in Factory Pattern
What are the real benefits of using the Abstract Factory in the following example, instead of the factory method?
I think in your example a factory seem useless because your Cake and Chocolate constructors don't need any args.
A factory is useful when you want to construct a complex object with many args to respect the DIP (Dependency Inversion Principle) and avoid embarrassing couplings.
In addition, your example seems to violate the LSP (Liskov Substitution Principle). Cake and Chocolate classes have nothing in common, and as evidence, your abstract super class is named Item which is a very generic name.
For me, with complex uncommon objects, the choice of one factory by class is better, and effectively respect the OCP (Open Closed Principle).
Your first example can be useful to instantiate classes which inherits the same superclass, but using your classes as arg and reflection (using java.lang.reflect) to call the constructor not just using String evaluation. (Your IDE is not able to autocomplete that) and in case of no match don't return null, Throw an IllegalArgumentException, it's more correct.
Like this :
import java.lang.reflect.Constructor;
public class SimpleItemFactory {
public <T extends Item> T createItem(Class<? extends Item> itemClass) {
try {
// construct your dependencies here
// and inject them in the getConstructor
Constructor<? extends Item> constructor = itemClass.getConstructor();
return (T)constructor.newInstance();
} catch (Exception e) {
throw new IllegalArgumentException();
}
}
}
and use it like this :
class Client {
public static void main(String[] args) {
SimpleItemFactory factory = new SimpleItemFactory();
IceCream iceCream = factory.createItem(IceCream.class);
System.out.println(iceCream);
Cake cake = factory.createItem(Cake.class);
System.out.println(cake);
Chocolate chocolate = factory.createItem(Chocolate.class);
System.out.println(chocolate);
}
}
If you have no dependencies you can implement the createItem() method as static directly in your abstract Item class.
See this book, it's a great resource : Head First Design Patterns
OCP is just Open for extension Close for modification Principle. If you need to open for modification your factory to add a new class (a new case to manage in a switch or a if), no, your factory is not "OCP".
You sould'nt calculate a tax in a constructor, a constructor should just... construct an object.. You could use a pattern like strategy to have many taxesCalculator and inject them into a constructor, with an IOC (Inversion of Control) mechanism like dependencies injection or in a simple way with.....a factory (it's acceptable), but not with a simple static method in your class.
I'm sorry for my bad english, it's difficult for me to answer to a complex question like this.

Understanding Abstract Factory pattern

I've read about abstract factory patter on wiki. But I don't understand really profit by using this pattern. Can you get an example in which is hard to avoid abstract factory pattern. Consider the following Java code:
public abstract class FinancialToolsFactory {
public abstract TaxProcessor createTaxProcessor();
public abstract ShipFeeProcessor createShipFeeProcessor();
}
public abstract class ShipFeeProcessor {
abstract void calculateShipFee(Order order);
}
public abstract class TaxProcessor {
abstract void calculateTaxes(Order order);
}
// Factories
public class CanadaFinancialToolsFactory extends FinancialToolsFactory {
public TaxProcessor createTaxProcessor() {
return new CanadaTaxProcessor();
}
public ShipFeeProcessor createShipFeeProcessor() {
return new CanadaShipFeeProcessor();
}
}
public class EuropeFinancialToolsFactory extends FinancialToolsFactory {
public TaxProcessor createTaxProcessor() {
return new EuropeTaxProcessor();
}
public ShipFeeProcessor createShipFeeProcessor() {
return new EuropeShipFeeProcessor();
}
}
// Products
public class EuropeShipFeeProcessor extends ShipFeeProcessor {
public void calculateShipFee(Order order) {
// insert here Europe specific ship fee calculation
}
}
public class CanadaShipFeeProcessor extends ShipFeeProcessor {
public void calculateShipFee(Order order) {
// insert here Canada specific ship fee calculation
}
}
public class EuropeTaxProcessor extends TaxProcessor {
public void calculateTaxes(Order order) {
// insert here Europe specific tax calculation
}
}
public class CanadaTaxProcessor extends TaxProcessor {
public void calculateTaxes(Order order) {
// insert here Canada specific tax calculation
}
}
If we need to just create objects in a code below 1-2 times in a code then we can use just new operator. And why we need in abstract factory?
You are missing half of the work :)
void processOrder(FinancialToolsFactory ftf,Order o) {
tft.createTaxProcessor().calculateTaxes(o);
tft.createShipFeeProcessor().calculateShipFee(o);
}
this code works as well as you pass a canadian or european implementation of FinancialToolsFactory (you can externalize the implementor class to external resource and instantiate with a Class.newInstance(), for example).
In this case one of the real benefits of pattern usage is not writing the code that implements the pattern, but who use that code!
PS: My answer is intentionally incomplete and try to answer just this specific question; a discussion about pattern and their benefits is too big!
You'd take advantage of this pattern if you were to support different implementations transparently. By delegating the decision of which implementation to use to the factory, you have a single point in your code where that decision is made (a.k.a. single responsibility).
The abstract factory pattern takes this concept beyond by aggregating related factories, such as different financial tools factories in your sample.
Now, if you only instantiate your financial tools once or twice in your code, using factories is over-engineering. The gain comes when you need to instantiate different implementations of the same interfaces in different places many times and you want to be able to work without worrying about which implementation you are using or how that decision is made.
There are quite some resources about this pattern on the web, and it's hard to guess what might be the best way of explaining its purpose in a way that sounds "plausible" for you.
But I think that the key point is:
With this pattern, someone who wants to create an instance of a particular implementation of an interface does not need to know what this particular implementation is. The call to the new operator is hidden inside the factory, and the user of the factory does not need to know the concrete class.
This makes it easier to switch the implementation later: You don't have to find and adjust all places where new ConcreteClass() was called and change it to new OtherConcreteClass() in order to use a different implementation. You just pass a different factory around, and everybody who uses this factory automatically creates instances of OtherConcreteClass (without even knowing that he does so...)

Interfaces in java

Code 1:
public class User1 implements MyInterface
{
#Override
public void doCalculation() { }
}
public class User2 implements MyInterface
{
#Override
public void doCalculation() { }
}
interface MyInterface
{
public void doCalculation();
}
Code 2:
public class User1
{
public void doCalculation() { }
}
public class User2
{
public void doCalculation() { }
}
Here in my Code 1 I have MyInterface which has an empty method doCalculation().
That doCalculation() is used by user1 and user2 by implementing MyInterface.
Where as in my Code 2 I have two different classes with defined doCalculation() method.
In both the cases code1 and code2 I myself have to write the implementation. My method doCalculation() is just an empty method.
So what is the use of MyInterface here?
It only provides me the method name or skeleton (is that the only advantage of interface)?
Or else would I save any memory while using MyInterface?
Is that, it only provides the empty method for an class which implements it, then why not I define it by myself as I have done in my code2.
More than that is there any more advantage on using an interface.
Interfaces are used a lot because they are basically a blueprint of what your class should be able to do.
For example, if you are writing a video game with characters, you can have an interface that holds all the methods that a character should have.
For example
public interface Character {
public void doAction();
}
And you have 2 characters, for example an ally and an enemy.
public class Ally implements Character {
public void doAction() {
System.out.println("Defend");
}
}
public class Enemy implements Character {
public void doAction() {
System.out.println("Attack");
}
}
As you can see, both classes implement the interface, but they have different actions.
Now you can create a character which implements your interface and have it perform its action. Depending on if it's an enemy or an ally, it'll perform a different action.
public Character ally = new Ally();
public Character enemy = new Enemy();
And in your main program, you can create a method that accepts any object that implements your interface and have it perform it's action without knowing what kind of character it is.
void characterDoAction(Character char) {
char.doAction();
}
If you would give ally to this method, the output would be:
Defend
If you would give enemy to this method, the output would be:
Attack
I hope this was a good enough example to help you understand the benefits of using interfaces.
There are a lot of advantages of interface driven programming.
What does "program to interfaces, not implementations" mean?
Basically you are defining a contract in an interface and all the classes which implement the interface have to abide by the contract.
Answers to your queries:
1.It only provides me the method name or skeleton (is that the only advantage of interface)?
--> Its not just about providing the method name but also defining what the class implementing the interface can do.
2.Or else would I save any memory while using MyInterface?
--> Nothing to do with the memory
Is that, it only provides the empty method for an class which implements it, then why not I define it by myself as I have done in my code2.
--> see the advantages of interface driven programming.
4.More than that is there any more advantage on using an interface.
--> Plenty,specially dependency injection , mocking , unit testing etc.
A very good explanation can be found here when-best-to-use-an-interface-in-java. It really depends on what you're building and how much scalability, code duplications, etc you want/don't want to have.
Many classes use interfaces to perform some function, relying on other programmers to implement that interface respecting the contract that an interface govern. Such classes are, for example, KeyListeners, MouseListeners, Runnable, etc.
For example: JVM knows what to do with a Thread, how to start it, stop it, manipulate it, but it does not know what your Thread should do, so you have to implement the Runnable interface.
Interfaces offer you a level of abstraction which can be leveraged in other classes. For example, if you have an interface called GemetricFigure, in a class that prints girth of a GeometricFigure you could iterate over a list of all GeometricFigures like:
public class Canvas {
private List<GeometricFigure> figures;
public void print() {
for (GeometricFigure figure : figure) {
System.out.println(figure.getGirth());
}
}
}
And if the GeometricFigure has only that method:
public interface GeometricFigure {
public Double getGirth();
}
You wouldn't care how Square or Circle implement that interface. Otherwise, if there were no interface, you could not have a list of GeometricFigures in Canvas, but a list for every figure type.
With the interface approach you can do the following:
List<MyInterface> list = new ArrayList<MyInterface();
list.add(new User1());
list.add(new User2());
for(MyInterface myInterface : list) {
myInterface.doClaculation()
}
This does not work with the second approach. Interfaces are for the code that use your classes - not for your classes themselves.
You can use interfaces in many cases. Also the situation you describes: You needn't to know, which implementation you have.
For example you have anywhere in your code a method, that returns the current singed in user even you don't know if it is User1 or User2 implementation, however that both of them can calculate something by method doCalculation. I add a really dummy example of that situation:
public void dummyExampleCalculation() {
getCurrentUser().doCalculation();
}
public MyInterface getCurrentUser() {
if(...) {
return new User1();
} else {
return new User2();
}
}
That is what Object Oriented Programming is all about.Interfaces are used to perform polymorphism. You said, you can implementations in code2 for both the classes, what if in future there is user3 who needs to doCalculation. You can just implement that interface and write your calculation in your own form.
When you want to provide a basic functionality to all your users abstract classes comes into picture where in you can declare an abstract method do calculation and provide implementation of that basic functionalities which then each user will extend and can doCalculation in their own way.
Interface is like a contract that your implementing class should satisfy. Usually, you will write an interface and make all your other class's implement it with their own implementation.
Example:
interface IExporter {
public void export();
}
public class PDFExport implements IExporter {
public void export(){
//code for PDF Exporting
}
}
public class XLSExport implements IExporter {
public void export(){
//code for XLS Exporting
}
}
public class DOCExport implements IExporter {
public void export(){
//code for DOC Exporting
}
}
Interface in Java is used to impose an implementation rule on classes. That means you can declare the signature of functions in interfaces and then implement these function in various classes by exactly following the function signature.
You can see a clear and realistic example on the following webpage
http://www.csnotes32.com/2014/10/interface-in-java.html

Java - Dynamic Class Casting from Interface to Implementation

I have read other related posts, but am still not quite sure how, or if it is possible to dynamically cast (interface to implementation) in Java. I am under the impression that I must use reflection to do so.
The particular project I am working on requires a usage of many instanceof checks, and it is — in my opinion — getting a bit out of hand, so would appreciate any ideas/solutions.
Below is a mini example I wrote up just to clarify exactly what I'm wanting to do. Let me know if you need more information:
Interface:
public interface IRobot {
String getName();
}
Implementations:
public class RoboCop implements IRobot {
String name = this.getClass()+this.getClass().getName();
public RoboCop() {}
public String getName() { return name; }
}
public class T1000 implements IRobot {
String name = this.getClass()+this.getClass().getName();
public T1000() {}
public String getName() { return name; }
}
The class that handles the implementations:
import java.util.LinkedList;
import java.util.List;
public class RobotFactory {
public static void main(String[] args) {
new RobotFactory();
}
public RobotFactory() {
List<IRobot> robots = new LinkedList<IRobot>();
robots.add( new RoboCop() );
robots.add( new T1000() );
System.out.println("Test 1 - Do not cast, and call deploy(robot)");
for(IRobot robot : robots) {
deploy(robot); // deploy(Object robot) will be called for each..
}
System.out.println("Test 2 - use instanceof");
for(IRobot robot : robots) { // use instanceof, works but can get messy
if(robot instanceof RoboCop) {
deploy((RoboCop)robot);
}
if(robot instanceof T1000) {
deploy((T1000)robot);
}
}
System.out.println("Test 3 - dynamically cast using reflection?");
for(IRobot robot : robots) {
//deploy((<Dynamic cast based on robot's type>)robot); // <-- How to do this?
}
}
public void deploy(RoboCop robot) {
System.out.println("A RoboCop has been received... preparing for deployment.");
// preparing for deployment
}
public void deploy(T1000 robot) {
System.out.println("A T1000 has been received... preparing for deployment.");
// preparing for deployment
}
public void deploy(Object robot) {
System.out.println("An unknown robot has been received... Deactivating Robot");
// deactivate
}
}
Output:
[RoboCop#42e816, T1000#9304b1]
Test 1 - Do not cast, and call deploy(robot)
An unknown robot has been received... Deactivating Robot
An unknown robot has been received... Deactivating Robot
Test 2 - use instanceof
A RoboCop has been received... preparing for deployment.
A T1000 has been received... preparing for deployment.
Test 3 - dynamically cast using reflection?
So, to sum up my question, how can I completely avoid having to use instanceof in this case. Thanks.
You can make deploy a method of IRobot, or use the visitor pattern.
And no, reflection will not make things any easier here.
Kent Beck says in his book Test Driven Development: Any time you're using run-time type-checking, polymorphism should help. Put the deploy() method in your interface and call it. You'll be able to treat all of your robots transparently.
Forget Reflection, you're just over thinking it. Remember your basic Object Oriented principles.
Dispatch of overloaded methods is done statically at compiletime, so your approach cannot be made to work. It's also very bad design. Doesn't it strike you as peculiar that the getName() method, the only thing that differs between the robot classes, is never actually called?
You have to ditch the overloaded methods, and instead use method overriding of methods in the robot classes, which you call directly. i.e.
public void deploy(IRobot robot) {
System.out.println("A "+robot.getName()+" has been received..."
+" preparing for deployment.");
// preparing for deployment
}
You can avoid instanceof by moving the deploy method in your IRobot interface and implementations.
The explanation of the behavior is that your three deploy methods are three different methods; overloaded methods with different signatures. At compile time, it's determined which one is chosen, not at runtime based on the real class...
Instead of using instanceof you can use the Factory Method Pattern
Definition of Factory method...
Like other creational patterns, it
deals with the problem of creating
objects (products) without specifying
the exact class of object that will be
created.
You will need a RobotCreatorFactory that will have a method called IRobot createRobot(String robotName) {...} (seeing that your robot returns a name. My suggestions is that each robot will have a public static String name NAME = Robocop.class.getName();. Inside the method you'll have a check such as
if (Robocop.NAME.equals(robotName) { return new RoboCop(); }
That way, you alleviate instanceof. And also, you can use #Meriton's advice on a DeploymentVisitor (using a visitor pattern)....
PS My example is a rough explanation of the Factory method pattern. An example exists in GoF book and Wikipedia.

Categories

Resources