浅析设计模式之享元设计模式
Posted Dszmr
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了浅析设计模式之享元设计模式相关的知识,希望对你有一定的参考价值。
享元模式的定义与特点
享元(Flyweight)模式的定义:运用共享技术来有効地支持大量细粒度对象的复用。它通过共享已经存在的又像来大幅度减少需要创建的对象数量、避免大量相似类的开销,从而提高系统资源的利用率。
享元模式的主要优点是:相同对象只要保存一份,这降低了系统中对象的数量,从而降低了系统中细粒度对象给内存带来的压力。
其主要缺点是:
为了使对象可以共享,需要将一些不能共享的状态外部化,这将增加程序的复杂性。
读取享元模式的外部状态会使得运行时间稍微变长。
代码实现
package cn.dszmr.sjms.xyms;
/**
* 实体对象
*/
public class UnsharedConcreteFlyweight {
private String key;
public UnsharedConcreteFlyweight(String key) {
this.key = key;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
package cn.dszmr.sjms.xyms;
/**
* 享元接口
*/
public interface Flyweight {
void operation(UnsharedConcreteFlyweight state);
}
package cn.dszmr.sjms.xyms;
/**
* 具体享元类
*/
public class ConcreteFlyweight implements Flyweight {
private String key;
public ConcreteFlyweight(String key) {
this.key = key;
System.out.println("key被创建");
}
@Override
public void operation(UnsharedConcreteFlyweight state) {
System.out.print("具体享元"+key+"被调用,");
System.out.println("非享元信息是:"+state.getKey());
}
}
package cn.dszmr.sjms.xyms;
import java.util.HashMap;
/**
* 享元工厂
*/
public class FlyweightFactory {
private HashMap<String,Flyweight> flyweights = new HashMap<>();
public Flyweight getFlyweight(String key){
Flyweight flyweight = flyweights.get(key);
if (flyweight != null){
System.out.println(key+"已存在并且被成功获取!");
}else {
flyweight = new ConcreteFlyweight(key);
flyweights.put(key,flyweight);
}
return flyweight;
}
}
package cn.dszmr.sjms.xyms;
/**
* 测试类
*/
public class FlyweightPattern
{
public static void main(String[] args)
{
FlyweightFactory factory=new FlyweightFactory();
Flyweight f01=factory.getFlyweight("a");
Flyweight f02=factory.getFlyweight("a");
Flyweight f03=factory.getFlyweight("a");
Flyweight f11=factory.getFlyweight("b");
Flyweight f12=factory.getFlyweight("b");
f01.operation(new UnsharedConcreteFlyweight("第1次调用a。"));
f02.operation(new UnsharedConcreteFlyweight("第2次调用a。"));
f03.operation(new UnsharedConcreteFlyweight("第3次调用a。"));
f11.operation(new UnsharedConcreteFlyweight("第1次调用b。"));
f12.operation(new UnsharedConcreteFlyweight("第2次调用b。"));
}
}
以上是关于浅析设计模式之享元设计模式的主要内容,如果未能解决你的问题,请参考以下文章