展会信息港展会大全

php设计模式 建造者模式 与Adapter(适配器模式)
来源:互联网   发布日期:2015-10-02 16:21:13   浏览:1073次  

导读: php教程设计模式 建造者模式 与Adapter(适配器模式)适配器模式 * * 将一个类的接口转换成客户希望的另外一个接口,使用原本不兼容的而不能在一起工作的那些类可以在一起工作...

php教程设计模式 建造者模式 与Adapter(适配器模式)

适配器模式

*

* 将一个类的接口转换成客户希望的另外一个接口,使用原本不兼容的而不能在一起工作的那些类可以在一起工作

建造者模式

*

* 将一个复杂对象的构建与它的表示分离,使用同样的构建过程可以创建不同的表示

<?php

/**

* 适配器模式

*

* 将一个类的接口转换成客户希望的另外一个接口,使用原本不兼容的而不能在一起工作的那些类可以在一起工作

*/

// 这个是原有的类型

class OldCache

{

public function __construct()

{

echo "OldCache construct<br/>";

}

public function store($key,$value)

{

echo "OldCache store<br/>";

}

public function remove($key)

{

echo "OldCache remove<br/>";

}

public function fetch($key)

{

echo "OldCache fetch<br/>";

}

}

interface Cacheable

{

public function set($key,$value);

public function get($key);

public function del($key);

}

class OldCacheAdapter implements Cacheable

{

private $_cache = null;

public function __construct()

{

$this->_cache = new OldCache();

}

public function set($key,$value)

{

return $this->_cache->store($key,$value);

}

public function get($key)

{

return $this->_cache->fetch($key);

}

public function del($key)

{

return $this->_cache->remove($key);

}

}

$objCache = new OldCacheAdapter();

$objCache->set("test",1);

$objCache->get("test");

$objCache->del("test",1);

php设计模式 Builder(建造者模式)

<?php

/**

* 建造者模式

*

* 将一个复杂对象的构建与它的表示分离,使用同样的构建过程可以创建不同的表示

*/

class Product

{

public $_type = null;

public $_size = null;

public $_color = null;

public function setType($type)

{

echo "set product type<br/>";

$this->_type = $type;

}

public function setSize($size)

{

echo "set product size<br/>";

$this->_size = $size;

}

public function setColor($color)

{

echo "set product color<br/>";

$this->_color = $color;

}

}

$config = array(

"type"=>"shirt",

"size"=>"xl",

"color"=>"red",

);

// 没有使用bulider以前的处理

$oProduct = new Product();

$oProduct->setType($config['type']);

$oProduct->setSize($config['size']);

$oProduct->setColor($config['color']);

// 创建一个builder类

class ProductBuilder

{

var $_config = null;

var $_object = null;

public function ProductBuilder($config)

{

$this->_object = new Product();

$this->_config = $config;

}

public function build()

{

echo "--- in builder---<br/>";

$this->_object->setType($this->_config['type']);

$this->_object->setSize($this->_config['size']);

$this->_object->setColor($this->_config['color']);

}

public function getProduct()

{

return $this->_object;

}

}

$objBuilder = new ProductBuilder($config);

$objBuilder->build();

$objProduct = $objBuilder->getProduct();

赞助本站

人工智能实验室

相关热词: php 教程

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港