written by sohyeon, hyemin ๐ก
ํฉํ ๋ฆฌ ๋ฉ์๋ ํจํด(Factory Method Pattern)๊ฐ์ฒด ์งํฅ ๋์์ธ ํจํด
์ด๋ค.
Factory method๋ ๋ถ๋ชจ(์์) ํด๋์ค์ ์๋ ค์ง์ง ์์ ๊ตฌ์ฒด ํด๋์ค๋ฅผ ์์ฑํ๋ ํจํด์ด๋ฉฐ.
์์(ํ์) ํด๋์ค๊ฐ ์ด๋ค ๊ฐ์ฒด๋ฅผ ์์ฑํ ์ง๋ฅผ ๊ฒฐ์ ํ๋๋ก ํ๋ ํจํด์ด๊ธฐ๋ ํ๋ค.
๋ถ๋ชจ(์์) ํด๋์ค ์ฝ๋์ ๊ตฌ์ฒด ํด๋์ค ์ด๋ฆ์ ๊ฐ์ถ๊ธฐ ์ํ ๋ฐฉ๋ฒ์ผ๋ก๋ ์ฌ์ฉํ๋ค.
์ฝ๊ฒ ๋งํด, ๊ฐ์ฒด ์์ฑ ๋ก์ง์ Factory๋ผ๋ ํด๋์ค๋ก ๋ถ๋ฆฌํ ํ
๊ฐ์ฒด ์ธ์คํด์คํ๋ฅผ ๋ถ๋ชจ ํด๋์ค๊ฐ ์๋ subclass์ ์์ํ๋ ํจํด์ด๋ค.
-
Creator
- abstract factory method๋ฅผ ์ ์
- factory method๋ฅผ ํธ์ถํด "Product"๋ฅผ ์์ฑ
-
Concrete Creator
- factory method๋ฅผ ๊ตฌํ, concrete product instance ์ค ํ๋๋ฅผ ๋ฐํ
-
Product
- factory method์ ์ํด ์์ฑ๋๋ product์ base class ํน์ interface
-
Concrete Product์ ์ญํ
- Product interface or class ๊ตฌํ
<์๋๋ฆฌ์ค>
์ฌ๋ฌ ๋ชจ์์ ๋ํ์ด ์กด์ฌํ ๋ ๊ฐ ๋ํ ๊ฐ์ฒด๋ฅผ ๋ฐํ ํ ๋ํ์ ๊ทธ๋ฆฝ๋๋ค.
// Shape.java
public interface Shape {
void draw();
}
// Circle.java
public class Circle implements Shape {
@Override
public void draw(){
System.out.println("Circle draw");
}
}
// Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw(){
System.out.println("Rectangle draw");
}
}
// Square.java
public class Square implements Shape {
@Override
public void draw(){
System.out.println("Square draw");
}
}
// ShapeFactory.java
public class ShapeFctory {
// Factory Method -> Product ์์ฑ ํ ๋ฐํ
public Shape getShape(String shapeType) {
if(shapeType == null) {
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
} else if(shapeType.equalsIgnoreCase("SQUARE")) {
return new Square();
}
return null;
}
}
public class FactoryPatternEx {
public static void main(String[] args) {
// ํฉํ ๋ฆฌ ํด๋์ค ๊ฐ์ฒด ์์ฑ
ShapeFactory shapeFactory = new ShapeFactory();
// ์ํ ์ธ์คํด์ค๋ฅผ ์์ฑ
Shape circle = shapeFactory.getShape("CIRCLE");
circle.draw();
// ์ผ๊ฐํ ์ธ์คํด์ค๋ฅผ ์์ฑ
shape rectangle = shapeFactory.getShape("RECTANGLE");
rectangle.draw();
// ์ฌ๊ฐํ ์ธ์คํด์ค๋ฅผ ์์ฑ
shape square = shapeFactory.getShape("SQUARE");
square.draw();
}
}
- Factory method pattern์ ๊ธฐ์กด ์ฝ๋๋ฅผ ์์ ํ์ง ์๊ณ , ํด๋์ค๋ฅผ ์ถ๊ฐํ๋ ๋ฐฉ์์ผ๋ก ์๋ก์ด ๊ฐ์ฒด ์์ฑ์ ์ฒ๋ฆฌํ ์ ์๋ค.
- ์๋ก์ด Product๊ฐ ์ถ๊ฐ๋ ๋๋ง๋ค class๋ฅผ ์ถ๊ฐํ๊ฒ ๋๋ฏ๋ก, ์ ์ ํด๋์ค๊ฐ ๋ง์์ง๋ค.
-> ๊ฒฝ์ฐ์ ๋ง๋ ์ฌ์ฉ์ด ๋์์ธ ํจํด์ ํจ์จ์ ๊ทน๋ํ ํ ์ ์๋ ๋ฏ ํ๋ค.