모듈 기능을 확장하거나 변경할 때 매번 핵심
코드를 수정해야한다.
Product 생성자가 변경된 경우 각각의 User클래스에 있는
모든 Product객체의 생성자 변경 필요
class Product {
init(){}
}
class UserA{
public func doMethod(){
let p = Product{}
}
}
class UserB{
public func doMethod(){
let p = Product{}
}
}
Factory에 getInstance() 메소드 내부에 있는 Product 생성자만 바꾸면된다.
class Product {
init(){}
}
class Factory{
public static getInstance() -> Product{
return Product();
}
}
class UserA{
public func doMethod(){
let p = Factory.getInstance();
}
}
프로토콜 생성
protocol Shape {
func draw()
}
클래스 생성
class Rectangle : Shape {
func draw() {
print("Inside Rectangle::draw() method")
}
}
class Square : Shape {
func draw() {
print("Inside Square::draw() method")
}
}
class Circle : Shape {
func draw() {
print("Inside Circle::draw() method")
}
}
Factory(객체 생성관련 코드만 모은 곳)
class ShapeFactory {
public func getShape(shapeType : String) -> Shape? {
if shapeType == nil {
return nil
}
if shapeType == "CIRCLE" {
return Circle()
}
else if shapeType == "RECTANGLE" {
return Rectangle()
}
else if shapeType == "SQUARE"{
return Square()
}
return nil
}
}
사용예제
let shapeFactory = ShapeFactory()
let shape1 = shapeFactory.getShape(shapeType: "CIRCLE")
shape1?.draw()
let shape2 = shapeFactory.getShape(shapeType: "RECTANGLE")
shape2?.draw()
let shape3 = shapeFactory.getShape(shapeType: "SQUARE")
shape3?.draw()