Skip to main content

Abstract Factory Pattern

View all Design Patterns

"A factory of factories".

Class Diagram

이를 보면, AnimalFactory를 구성하는 DuckFactory, CatFactory를 보면 각각 같은 범주로 묶어, 하위 객체들의 생성을 관리하도록 한다. 이렇게 연관된 객체들을 하나의 팩토리에서 생성할 수 있다.


Code

interface Animal {
sound(): string;
}

interface Breeder {
getLicense(): string;
}

class Duck implements Animal {
sound(): string {
return "Quack";
}
}

class Cat implements Animal {
sound(): string {
return "Meow";
}
}

class DuckBreeder implements Breeder {
getLicense(): string {
return "Duck Breeder License";
}
}

class CatBreeder implements Breeder {
getLicense(): string {
return "Cat Breeder License";
}
}

interface AnimalFactory {
createAnimal(): Animal;
createBreeder(): Breeder;
}

class DuckFactory implements AnimalFactory {
createAnimal(): Animal {
return new Duck();
}

createBreeder(): Breeder {
return new DuckBreeder();
}
}

class CatFactory implements AnimalFactory {
createAnimal(): Animal {
return new Cat();
}

createBreeder(): Breeder {
return new CatBreeder();
}
}

// when client creates instances
const duckFactory = new DuckFactory();
const catFactory = new CatFactory();

const duck = duckFactory.createAnimal();
const duckBreeder = duckFactory.createBreeder();
const cat = catFactory.createAnimal();
const catBreeder = catFactory.createBreeder();

console.log(`duck sounds ${duck.sound()}`);
console.log(`duck breeder has ${duckBreeder.getLicense()}`);
console.log(`cat sounds ${cat.sound()}`);
console.log(`cat breeder has ${catBreeder.getLicense()}`);

Pros and Cons

Pros

  • 클라이언트의 코드 변경없이 추가적인 팩토리 클래스를 추가하기 용이하다.

Cons

Related Links