美文网首页
享元模式-flyweight

享元模式-flyweight

作者: HeJD | 来源:发表于2018-04-19 15:33 被阅读0次

    运用共享技术有效地支持大量细粒度的对象

    这里写图片描述
    实际上就是通过一个容器存储对象,等到需要用的时候,再获取对象的引用

    优点:

     减少对象数量,节省内存空间
    

    缺点:

     维护共享对象需要额外开销,如需要专门设置一个线程来回收
    

    代码:

    Main

    public class Main {
    
        public static void main(String[] args) {
            Flyweight f1,f2,f3,f4;
            FlyweightFactory factory=new FlyweightFactory();
            
            f1=factory.getFlyWeight("he");
            f2=factory.getFlyWeight("jd");
            f3=factory.getFlyWeight("he");
            f4=factory.getFlyWeight("he");
            
            f1.operation();f2.operation();f3.operation();f4.operation();
            System.out.println(factory.getFlyWeightSize());
        }
    
    }
    

    abs:FlyWeight

    public abstract class Flyweight {
        public abstract void operation();
    }
    

    imp:ConcreteFlyWeight

    public class ConcreteFlyweight extends Flyweight {
    
        private String name;
        public ConcreteFlyweight(String name){
            this.name=name;
        }
        @Override
        public void operation() {
            System.out.println("this is concrete flyweight name is "+this.name);
        }
    
    }
    

    imp:FlyWeightFactory

    public class FlyweightFactory {
        
        private Map flyweight=new HashMap<Object, Object>();
        
        public Flyweight getFlyWeight(Object obj){
            Flyweight temp=(Flyweight) this.flyweight.get(obj);
            if(temp==null){
                temp=new ConcreteFlyweight((String) obj);
                this.flyweight.put(obj, temp);
            }
            return temp;
        }
        public int getFlyWeightSize(){
            return this.flyweight.size();
        }
    
    }
    

    相关文章

      网友评论

          本文标题:享元模式-flyweight

          本文链接:https://www.haomeiwen.com/subject/vnxvcftx.html