享元模式:运用共享技术有效地支持大量细粒度的对象。

适用场合:假设一个应用程序适用了大量的对象。而大量的这些对象造成了非常大的存储开销时就应该考虑使用。

首先定义一个IFlyweight接口

public interface IFlyweight {

    public void operation(int extrinsicstate);
}

接着定义一个ConcreteFlyweight继承IFlyweight

public class ConcreteFlyweight implements IFlyweight{

    @Override
public void operation(int extrinsicstate) { System.out.println("详细flyweight:"+extrinsicstate); } }

再定义一个UnsharedConcreteFlyweight继承IFlyweight

public class UnsharedConcreteFlyweight implements IFlyweight{

    @Override
public void operation(int extrinsicstate) { System.out.println("不共享的详细flyweight:"+extrinsicstate); }
}

然后定义一个FlyweightFactory

public class FlyweightFactory {

    Map<String, IFlyweight> flyweights=new HashMap<String,IFlyweight>();

    public FlyweightFactory(){
flyweights.put("x", new ConcreteFlyweight());
flyweights.put("y", new ConcreteFlyweight());
flyweights.put("z", new ConcreteFlyweight());
} public IFlyweight getFlyweight(String key){
return flyweights.get(key);
}
}

client代码

public static void main(String[] args) {
//享元模式
int extrinsicstate=22;
FlyweightFactory factory=new FlyweightFactory(); IFlyweight fx=factory.getFlyweight("x");
fx.operation(--extrinsicstate); IFlyweight fy=factory.getFlyweight("y");
fy.operation(--extrinsicstate); IFlyweight fz=factory.getFlyweight("z");
fz.operation(--extrinsicstate); IFlyweight uf=new UnsharedConcreteFlyweight();
uf.operation(--extrinsicstate);
}

最新文章

  1. kvm 简介
  2. VMware Fusion 中如何复制centos/linux虚拟机
  3. 【Android】应用程序Activity启动过程分析
  4. NSURLSession/NSURLConnection的上传文件方法(已做了更新)
  5. selenium+python笔记9
  6. poj2429 大数分解+dfs
  7. 【UML】具体解释六种关系
  8. django 学习-12 Django表单 初步
  9. 一个.Net程序员:既然选择了编程,只管风雨兼程(转)
  10. 魅蓝Note2跑分 MT6753性能究竟如何
  11. Bash Shell 快捷键的学习使用
  12. Python之美[从菜鸟到高手]--生成器之全景分析
  13. 创建并使用静态库(ar 命令)
  14. Linux 程序,进程和线程
  15. Java 多态透析 详细理解
  16. 【原】eclipse创建maven工程时,如何修改默认JDK版本?
  17. eclipse如何正确部署tomcat7
  18. arcgis 画图工具
  19. 329 experience
  20. consul 文档

热门文章

  1. 优动漫PAINT-凌霄花画法
  2. 影像服务——加载CESIUM自带的影像服务
  3. angular7升级到angular8
  4. redhat7.5 升级OpenSSH_7.8p1
  5. 微信小程序 分享海报
  6. Python学习笔记(二):字符串类型
  7. Camera Calibration 相机标定:原理简介(五)
  8. mysql-高级语言语法
  9. Linux怎样改动root用户的password
  10. 【我们都爱Paul Hegarty】斯坦福IOS8公开课个人笔记3 Xcode、Auto Layout及MVC