C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > c++ Factory Method

c++ 创建型设计模式工厂方法Factory Method示例详解

作者:菜皮日记

这篇文章主要为大家介绍了c++ 创建型设计模式工厂方法Factory Method示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

简介

工厂方法中,每一个具体工厂类都对应创建一个具体产品类,所有具体工厂类都实现抽象工厂,所有具体产品类都实现抽象产品。

抽象工厂定义了创建抽象产品的方法签名,具体工厂类各自实现各自逻辑,来创建具体的产品。

角色

类图

如图所示,Dialog抽象工厂可以创建Button抽象产品,WindowsDialog和WebDialog都是具体工厂,负责创建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++ 创建型设计模式工厂方法Factory Method示例详解的详细内容,更多关于c++ Factory Method的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文