1. 程式人生 > >Design Patterns 3: Factory Method

Design Patterns 3: Factory Method

定義一個介面(Creator)用以建立物件,由子類(ConcreteCreator)決定建立物件的型別(Product或ConcreteProduct...)

struct Product {};

struct ConcreteProduct : Product {};

struct Creator
{
	virtual Product* FactoryMethod() { return new Product; }
	void AnOperation() { product = FactoryMethod(); }
private:
	Product * product;
};

struct ConcreteCreator : Creator
{
	Product* FactoryMethod() override { return new ConcreteProduct; }
};

int main()
{
	Creator* p = new ConcreteCreator;
	p->AnOperation();//ConcreteCreator::FactoryMethod() get called
}