《大话设计模式》享元模式-网站场景-PHP版代码

Standard

享元模式
网站场景

<?php
/**
 * 享元模式 网站场景
 * @author 叶茂盛 anson.ye#gmail.com  http://yemaosheng.com
 */
class User{
	public $name;
	public function __construct($name){
		$this->name = $name;
	}
}
 
abstract class WebSite{
	abstract function __construct(User $user);
}
 
class ConcreteWebSite extends Website{
 
	private $_name;
 
	public function __construct($name){
		$this->_name = $name;
	}
	public function User(User $user){
		echo "网站分类:" . $this->_name . " 用户:" . $user->name . "\n";
	}
}
 
class WebSiteFactory{
 
	private $_websites;
	private $_ConcreteWetSite;
 
	public function __construct(){
		$this->_ConcreteWetSite = array();
	}
 
	public function GetWebSiteCategory($key){
		if( isset($websites[$key]) ){
			return $this->_websites[$key];
		}else{
			return $this->_websites[$key] = new ConcreteWebSite($key);
		}
	}
	public function GetWebSiteCount(){
		return count( $this->_websites );
	}
}
 
class Main{
	public static function run(){
		$WebSiteFactory = new WebSiteFactory;
		$f = new WebSiteFactory();
		$fx = $f->GetWebSiteCategory("产品展示");
		$fx->User(new User("小菜"));
 
		$fy = $f->GetWebSiteCategory("产品展示");
		$fy->User(new User("大鸟"));
 
		$fy = $f->GetWebSiteCategory("产品展示");
		$fy->User(new User("娇娇"));
 
		$fl = $f->GetWebSiteCategory("博客");
		$fl->User(new User("老顽童"));
 
		$fm = $f->GetWebSiteCategory("博客");
		$fm->User(new User("六仙"));
 
		$fn = $f->GetWebSiteCategory("博客");
		$fn->User(new User("南海"));
 
		echo "得到网站分类总数为:" .$f->GetWebSiteCount(). "\n";
	}
}
Main::run();
?>
//php Flyweight.php 
//网站分类:产品展示 用户:小菜
//网站分类:产品展示 用户:大鸟
//网站分类:产品展示 用户:娇娇
//网站分类:博客 用户:老顽童
//网站分类:博客 用户:六仙
//网站分类:博客 用户:南海
//得到网站分类总数为:2

转载请注明出处 http://yemaosheng.com

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.