乐趣区

关于设计模式:创建型设计模式工厂方法-Factory-Method

简介

工厂办法中,每一个具体工厂类都对应创立一个具体产品类,所有具体工厂类都实现形象工厂,所有具体产品类都实现形象产品。

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

角色

  • 形象工厂 Abstract Factory

    定义创立产品的办法签名,即 Factory Method

  • 形象产品 Abstract Product

    定义产品的根本属性

  • 具体工厂 Concrete Factory

    实现自形象工厂,并实现 Factory Method,实现如何创立具体产品。

  • 具体产品 Concrete Product

    实现具体产品根本属性

类图

如图所示,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}
退出移动版