首页 技术 正文
技术 2022年11月16日
0 收藏 536 点赞 3,754 浏览 1366 个字

享元模式其实就是共享独享模式,减少重复实例化对象的操作,从而将实例化对象造成的内存开销降到最低。

享元模式尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。我们将通过创建 5 个对象来画出 20 个分布于不同位置的圆来演示这种模式。由于只有 5 种可用的颜色,所以 color 属性被用来检查现有的 Circle 对象。

<?phpinterface Shape{
public function draw();
}class Circle implements Shape{
private $color;
private $num; public function __construct($color){
$this->color = $color;
} public function draw(){
echo "this is a {$this->color} circle {$this->num} \n";
} public function setNum($num){
$this->num = $num;
}
}class ShapeFactory{
public static $shape_arr = []; public static function getShape($color){
if(!array_key_exists($color,static::$shape_arr)){
static::$shape_arr[$color] = new Circle($color);
}
return static::$shape_arr[$color];
}
}$colors = ["Red", "Green", "Blue", "White", "Black"];for ($i=0; $i < 20; $i++) {
$a = $i%5;
$circle = ShapeFactory::getShape($colors[$a]);
$circle->setNum($i);
$circle->draw();
}

输出

this is a Red circle 0
this is a Green circle 1
this is a Blue circle 2
this is a White circle 3
this is a Black circle 4
this is a Red circle 5
this is a Green circle 6
this is a Blue circle 7
this is a White circle 8
this is a Black circle 9
this is a Red circle 10
this is a Green circle 11
this is a Blue circle 12
this is a White circle 13
this is a Black circle 14
this is a Red circle 15
this is a Green circle 16
this is a Blue circle 17
this is a White circle 18
this is a Black circle 19

注意:享元模式适用于对象存在时间不长的情况,就像例子中画一个圆形只要这个圆形画完后其对象就没有意义啦,这时我们将这个对象的属性改变后成为一个新的对象是可以的。假设我们是在一个创建游戏人物的场景中使用,当创建了某个类型的英雄人物对象之后,我们想要再创建一个相同类型不同属性的英雄人物时,则不适合使用这种设计模式,因为后来的英雄人物对象会是前一个对象改变属性后生成的,这将导致之前的英雄就不存在啦。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,105
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,582
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,429
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,836
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,919