Design Pattern - Factory Pattern

 Factory pattern is one of the most used design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.


package com.company;

public interface Shape {
void draw();
}
package com.company;

public class Rectangle implements Shape{
@Override
public void draw() {
System.out.println("Rectangle");
}
}
package com.company;

public class Square implements Shape{
@Override
public void draw() {
System.out.println("Square");
}
}
package com.company;

public class Circle implements Shape{
@Override
public void draw() {
System.out.println("Circle");
}
}
package com.company;

public class ShapeFactory {

public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("Circle")){
return new Circle();
}else if(shapeType.equalsIgnoreCase("rectangele")){
return new Rectangle();
} else if (shapeType.equalsIgnoreCase("square")) {
return new Square();
}
return null;
}
}
package com.company;

public class Main {

public static void main(String[] args) {
Shape s = new ShapeFactory().getShape("circle");
s.draw();
}
}

Комментарии

Популярные сообщения из этого блога

Lesson1: JDK, JVM, JRE

SE_21_Lesson_11: Inheritance, Polymorphism

SE_21_Lesson_9: Initialization Blocks, Wrapper types, String class