享元模式

享元模式实现

FlyweightFacrory享元工厂类

创建并管理享元工厂类,享元池一般设计成键值对

FlyWeght抽象享元类

通常是一个接口或抽象类,声明公共方法,这些方法可以向外界提供对象的内部状态,设置外部状态

ConcreteFlyWeight具体享元类

为内部状态提供成员变量进行存储

UnsharedConcreteFlayWeight非共享享元类

不能被共享的子类可以设计为非共享享元类

public class UnsharedConcreteFlyWeight {

private Integer X;
private Integer y;

public UnsharedConcreteFlyWeight(Integer x, Integer y) {
super();
X = x;
this.y = y;
}
public Integer getX() {
return X;
}
public void setX(Integer x) {
X = x;
}
public Integer getY() {
return y;
}
public void setY(Integer y) {
this.y = y;
}
}


public interface ConcreteFlyWeight {
void display(UnsharedConcreteFlyWeight ucfw );
}


class ConcreteFlyWeightImpl implements ConcreteFlyWeight{
private String color;

public ConcreteFlyWeightImpl(String color) {
this.color = color;
}

@Override
public void display(UnsharedConcreteFlyWeight ucfw) {
System.out.println(this.color +" "+"x轴坐标"+ ucfw.getX() + "y轴坐标" + ucfw.getY());
}
}


public class FlyWeightFactory {
private static Map<String,ConcreteFlyWeightImpl> chessMap = new HashMap<String,ConcreteFlyWeightImpl>();

public static ConcreteFlyWeightImpl getChess(String color) {

if(chessMap.get(color) != null) {
return chessMap.get(color);
}else {
ConcreteFlyWeightImpl chess = new ConcreteFlyWeightImpl(color);
chessMap.put(color, chess);
return chess;
}
}
}


public class Client {
public static void main(String[] args) {
ConcreteFlyWeightImpl writeChess = FlyWeightFactory.getChess("白色");
ConcreteFlyWeightImpl blackChess = FlyWeightFactory.getChess("黑色");
writeChess.display(new UnsharedConcreteFlyWeight(10,20));
blackChess.display(new UnsharedConcreteFlyWeight(20,30));
}
}


享元模式开发中应用的场景

享元模式由于其共享特性,可以在任何"池"中操作,比如 线程池,数据库连接池。

String类的设计也是享元模式


优点

极大的减少内存中对象的数量

相同或相似的对象内存中只存一份,极大的节约资源,提供系统性能

外部状态相对独立,不影响内部状态

缺点

模式较为复杂,使程序逻辑复杂化

为了节省内存,共享内部状态,分离出外部状态,而读取外部状态使运行时间变长,用时间交换空间。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值