Prototype

godo·2022년 8월 15일
0

Swift - Design Patterns

목록 보기
4/24

복잡한 객체는 처음부터 만들어지지 않음
프로토타입을 복사해 커스터마이즈해서 사용 ( deep copy 가 필요 )
Factory 를 이용해서 복사를 쉽게 할 수 있음

Copy Constructors

class Address : CustomStringConvertible
{
    var streetAddress : String
    var city : String
    
    init(_ streetAddress: String, _ city: String)
    {
        self.streetAddress = streetAddress
        self.city = city
    }
    
    var description: String
    {
        return "\(streetAddress), \(city)"
    }
}

class Employee
{
    var name : String
    var address : Address
    
    init(_ name: String, _ address: Address)
    {
        self.name = name
        self.address = address
    }
    
    var description : String
    {
        return "My name is \(name) and I live at \(address)"
    }
}

func main()
{
    var john = Employee("John", Address("123 Seoul Road", "Seoul"))
    
    var chris = john
    chris.name = "Chris"
    chris.address.streetAddress = "244 Seoul Road"
    
    print(john.description)
    print(chris.description)
}

이렇게 값을 변경시키면 동시에 변경이 되는 데 이것을 struct 으로 바꾸면

struct Address
struct Employee

이렇게 나옵니다.

다른 방식을 사용하자면

protocol Copying
{
    init(copyFrom other: Self)
}

...

required init(copyFrom other: Address)
{
    streetAddress = other.streetAddress
    city = other.city
}


...

init(copyFrom other: Employee)
{
    name = other.name
        
    // 1 번째 방법
    // address = Address(other.address.streetAddress, other.address.city)
        
    // 2 번째 방법
    address = Address(copyFrom: other.address)
}

...


var john = Employee("John", Address("123 Seoul Road", "Seoul"))
    
var chris = Employee(copyFrom: john)
chris.name = "Chris"
chris.address.streetAddress = "244 Seoul Road"

이렇게 하면 됩니다.

Explicit Deep Copy Interface

protocol Copying
{
    
    // the 'required' keyword is only used in classes
//    init(copyFrom other: Self)
    func clone() -> Self

}

...

func clone() -> Self {
    return cloneImpl()
}
    
private func cloneImpl<T>() -> T
{
    return Address(streetAddress, city) as! T
}
     
...


func clone() -> Employee // <-- struct
{
    return Employee(name, address.clone())
}

...

var chris = john.clone()

정리

prototype 을 가져와 >> deep copy 사용 copy >> customizing

profile
☀️☀️☀️

0개의 댓글