设计模式之Flyweight模式(笔记)
2024-08-26 11:06:22
享元模式:运用共享技术有效地支持大量细粒度的对象。
适用场合:假设一个应用程序适用了大量的对象。而大量的这些对象造成了非常大的存储开销时就应该考虑使用。
首先定义一个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);
}
最新文章
- kvm 简介
- VMware Fusion 中如何复制centos/linux虚拟机
- 【Android】应用程序Activity启动过程分析
- NSURLSession/NSURLConnection的上传文件方法(已做了更新)
- selenium+python笔记9
- poj2429 大数分解+dfs
- 【UML】具体解释六种关系
- django 学习-12 Django表单 初步
- 一个.Net程序员:既然选择了编程,只管风雨兼程(转)
- 魅蓝Note2跑分 MT6753性能究竟如何
- Bash Shell 快捷键的学习使用
- Python之美[从菜鸟到高手]--生成器之全景分析
- 创建并使用静态库(ar 命令)
- Linux 程序,进程和线程
- Java 多态透析 详细理解
- 【原】eclipse创建maven工程时,如何修改默认JDK版本?
- eclipse如何正确部署tomcat7
- arcgis 画图工具
- 329 experience
- consul 文档