c++?創(chuàng)建型設計模式工廠方法Factory?Method示例詳解
簡介
工廠方法中,每一個具體工廠類都對應創(chuàng)建一個具體產(chǎn)品類,所有具體工廠類都實現(xiàn)抽象工廠,所有具體產(chǎn)品類都實現(xiàn)抽象產(chǎn)品。
抽象工廠定義了創(chuàng)建抽象產(chǎn)品的方法簽名,具體工廠類各自實現(xiàn)各自邏輯,來創(chuàng)建具體的產(chǎn)品。
角色
抽象工廠 Abstract Factory
定義創(chuàng)建產(chǎn)品的方法簽名,即Factory Method
抽象產(chǎn)品 Abstract Product
定義產(chǎn)品的基本屬性
具體工廠 Concrete Factory
實現(xiàn)自抽象工廠,并實現(xiàn) Factory Method,實現(xiàn)如何創(chuàng)建具體產(chǎn)品。
具體產(chǎn)品 Concrete Product
實現(xiàn)具體產(chǎn)品基本屬性
類圖
如圖所示,Dialog抽象工廠可以創(chuàng)建Button抽象產(chǎn)品,WindowsDialog和WebDialog都是具體工廠,負責創(chuàng)建WindownsButton和HTMLButton。

代碼
abstract class Creator
{
abstract public function factoryMethod(): Product;
public function someOperation(): string
{
$product = $this->factoryMethod();
$result = "Creator: The same creator's code has just worked with " . $product->operation();
return $result;
}
}
class ConcreteCreator1 extends Creator
{
public function factoryMethod(): Product
{
return new ConcreteProduct1();
}
}
class ConcreteCreator2 extends Creator
{
public function factoryMethod(): Product
{
return new ConcreteProduct2();
}
}
interface Product
{
public function operation(): string;
}
class ConcreteProduct1 implements Product
{
public function operation(): string
{
return "{Result of the ConcreteProduct1}";
}
}
class ConcreteProduct2 implements Product
{
public function operation(): string
{
return "{Result of the ConcreteProduct2}";
}
}
function clientCode(Creator $creator)
{
echo "Client: I'm not aware of the creator's class, but it still works.\n" . $creator->someOperation() . "\n";
}
echo "App: Launched with the ConcreteCreator1.\n";
clientCode(new ConcreteCreator1());
echo "App: Launched with the ConcreteCreator2.\n";
clientCode(new ConcreteCreator2());output
App: Launched with the ConcreteCreator1.
Client: I'm not aware of the creator's class, but it still works.
Creator: The same creator's code has just worked with {Result of the ConcreteProduct1}
App: Launched with the ConcreteCreator2.
Client: I'm not aware of the creator's class, but it still works.
Creator: The same creator's code has just worked with {Result of the ConcreteProduct2}
以上就是c++ 創(chuàng)建型設計模式工廠方法Factory Method示例詳解的詳細內(nèi)容,更多關(guān)于c++ Factory Method的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C++ 將文件數(shù)據(jù)一次性加載進內(nèi)存實例代碼
這篇文章主要介紹了C++ 將文件數(shù)據(jù)一次性加載進內(nèi)存實例代碼的相關(guān)資料,需要的朋友可以參考下2017-05-05
使用C語言實現(xiàn)vector動態(tài)數(shù)組的實例分享
vector是指能夠存放任意類型的動態(tài)數(shù)組,而C語言中并沒有面向?qū)ο蟮腃++那樣內(nèi)置vector類,所以我們接下來就來看一下使用C語言實現(xiàn)vector動態(tài)數(shù)組的實例,需要的朋友可以參考下2016-05-05

