[팩토리 메서드 패턴]
[추상 팩토리 패턴]
예제
1) Shape 인터페이스 생성
public interface Shape {
void draw();
}
2) Shape 인터페이스를 구현하는 구상 클래스 생성
[RoundedRectangle]
public class RoundedRectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside RoundedRectangle::draw() method.");
}
}
[RoundedSquare]
public class RoundedSquare implements Shape {
@Override
public void draw() {
System.out.println("Inside RoundedSquare::draw() method.");
}
}
[Rectangle]
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
3) 추상 클래스를 생성하여 객체를 생성할 수 있는 추상 팩토리 패턴을 만듬.
[AbstractFactory]
public abstract class AbstractFactory {
abstract Shape getShape(String shapeType) ;
}
4) AbstractFactory를 상속받아 구상클래스의 객체를 생성
[ShapeFactory]
public class ShapeFactory extends AbstractFactory {
@Override
public Shape getShape(String shapeType){
if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}
[RoundedShapeFactory]
public class RoundedShapeFactory extends AbstractFactory {
@Override
public Shape getShape(String shapeType){
if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new RoundedRectangle();
}else if(shapeType.equalsIgnoreCase("SQUARE")){
return new RoundedSquare();
}
return null;
}
}
5) FactoryProducer클래스를 생성하여 Shape 인터페이스의 정보를 사용할 수 있도록 함.
[FactoryProducer]
public class FactoryProducer {
public static AbstractFactory getFactory(boolean rounded){
if(rounded){
return new RoundedShapeFactory();
}else{
return new ShapeFactory();
}
}
}
6) FactoryProducer를 사용하여 각 도형 객체의 정보를 가져 올 수 있음.
[AbstractFactoryPatternDemo]
public class AbstractFactoryPatternDemo {
public static void main(String[] args) {
AbstractFactory shapeFactory = FactoryProducer.getFactory(false);
Shape shape1 = shapeFactory.getShape("RECTANGLE");
shape1.draw();
Shape shape2 = shapeFactory.getShape("SQUARE");
shape2.draw();
AbstractFactory shapeFactory1 = FactoryProducer.getFactory(true);
Shape shape3 = shapeFactory1.getShape("RECTANGLE");
shape3.draw();
Shape shape4 = shapeFactory1.getShape("SQUARE");
shape4.draw();
}
}
7) 출력 결과
Inside Rectangle::draw() method.
Inside Square::draw() method.
Inside RoundedRectangle::draw() method.
Inside RoundedSquare::draw() method.