zoukankan      html  css  js  c++  java
  • 设计模式之Flyweight模式(笔记)

    享元模式:运用共享技术有效地支持大量细粒度的对象。
    适用场合:假设一个应用程序适用了大量的对象。而大量的这些对象造成了非常大的存储开销时就应该考虑使用。
    这里写图片描写叙述

    首先定义一个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);
        }
  • 相关阅读:
    整数幂的求解
    非递归实现不重复序列的全排列(二)
    完整的将日期时间转换为汉字的代码
    如何得到某集合的所有子集合?
    再谈八皇后问题
    大数阶乘的计算(六)
    非递归实现不重复序列的全排列(一)
    非递归实现不重复序列的全排列(三)
    大数阶乘的计算(五)
    关于走楼梯的递归算法
  • 原文地址:https://www.cnblogs.com/mthoutai/p/6992663.html
Copyright © 2011-2022 走看看