随着开发时间越长好多设计模式逐渐记的不清晰了,重新回忆下,做下记录
- PHP单例模式(有个简单的短语“三私一公”)
简单来说就是三个私有方法,一个公有方法 __construct,__clone,$instance三个私用 对外提供一个公有获取实例的方法
<?php
class Singleton
{
private static $instance;
private function __construct()
{
echo 'no construct';
}
private function __clone()
{
echo 'no clone';
}
public static function getInstance()
{
if (self::$instance instanceof Singleton) {
return self::$instance;
}
return new self();
}
}
<?php
interface People
{
public function say();
}
class Man implements People
{
public function say()
{
echo 'I m Man \n';
}
}
class WoMan implements People
{
public function say()
{
echo 'I m Woman \n';
}
}
class SimpleFactory
{
public static function createMan()
{
return new Man();
}
public static function createWoMan()
{
return new WoMan();
}
}
$man = SimpleFactory::createMan();
$man->say();
$woMan = SimpleFactory::createWoMan();
$woMan->say();
<?php
interface People
{
public function say();
}
class Man implements People
{
public function say()
{
echo 'I m Man \n';
}
}
class WoMan implements People
{
public function say()
{
echo 'I m Woman \n';
}
}
interface FactoryCreator
{
public function create();
}
class CreateMan implements FactoryCreator
{
public function create()
{
return new Man();
}
}
class CreateWoman implements FactoryCreator
{
public function create()
{
return new Woman();
}
}
$creator = new CreateMan();
$man = $creator->create();
$man->say();
$creator = new CreateWoman();
$man = $creator->create();
$man->say();
- 抽象工厂
最少3个接口(品类1接口,品类2接口,抽象工厂接口),以及他们3个接口的实现类
<?php
interface Message
{
public function send();
}
class AliMessage implements Message
{
public function send()
{
echo 'Ali send message';
}
}
class JiguangMessage implements Message
{
public function send()
{
echo 'Jiguang send message';
}
}
class BaiduMessage implements Message
{
public function send()
{
echo 'Baidu send message';
}
}
interface Push
{
public function send();
}
class AliPush implements Push
{
public function send()
{
echo 'Ali send push';
}
}
class JiguangPush implements Push
{
public function send()
{
echo 'Jiguang send push';
}
}
class BaiduPush implements Push
{
public function send()
{
echo 'baidu send push';
}
}
interface AbstractFactory
{
public function createMessage();
public function createPush();
}
class AliAbstractFactory implements AbstractFactory
{
public function createMessage()
{
return new AliMessage();
}
public function createPush()
{
return new AliPush();
}
}
class JiguangAbstractFactory implements AbstractFactory
{
public function createMessage()
{
return new JiguangMessage();
}
public function createPush()
{
return new JiguangPush();
}
}
class BaiduAbstractFactory implements AbstractFactory
{
public function createMessage()
{
return new BaiduMessage();
}
public function createPush()
{
return new BaiduPush();
}
}
$AliFactory = new AliAbstractFactory();
$aliMessage = $AliFactory->createMessage();
$aliPush = $AliFactory->createPush();
$aliMessage->send();
$aliPush->send();
|