欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

设计模式笔记---享元模式

程序员文章站 2022-03-10 17:12:55
1、概念是池技术的重要实现方式,使用共享对象可有效地支持大量的细粒度的对象。2、说明Flyweight:抽象享元角色(一个产品的抽象类,同时定义出对象的外部状态和内部状态的接口或实现)public abstract class Flyweight { private String intrinsic; protected final String extrinstic; public Flyweight(String _extrinstic){...

1、概念

是池技术的重要实现方式,使用共享对象可有效地支持大量的细粒度的对象。

2、说明

Flyweight:抽象享元角色(一个产品的抽象类,同时定义出对象的外部状态和内部状态的接口或实现)

public abstract class Flyweight {
    private String intrinsic;

    protected  final String extrinstic;

    public Flyweight(String _extrinstic){
        this.extrinstic = _extrinstic;
    }

    public  abstract void operate();

    public String getIntrinsic() {
        return intrinsic;
    }

    public void setIntrinsic(String intrinsic) {
        this.intrinsic = intrinsic;
    }
}

ConcreFlyweight:具体享元单元(具体的一个产品类,实现抽象角色定义的义务)

public class ConcreFlyweight1 extends Flyweight {
    public ConcreFlyweight1(String _extrinstic) {
        super(_extrinstic);
    }

    @Override
    public void operate() {

    }
}

FlyweightFactory:享元工厂(构造一个池容器,同时提供从池中获得对象的方法)

public class FlyweightFactory {
    private static HashMap<String,Flyweight> pool = new HashMap<String, Flyweight>();

    public static Flyweight getFlyweight(String extrinstic){
        Flyweight flyweight = null;

        if(pool.containsKey(extrinstic)){
            flyweight = pool.get(extrinstic);
        }else{
            flyweight = new ConcreFlyweight1(extrinstic);
            pool.put(extrinstic,flyweight);
        }

        return flyweight;
    }
}

场景类:

public class Client {
    public static void main(String args[]){
        Integer times = 1000000000;
        String key = "test";
        FlyweightFactory.getFlyweight(key);

        Long t1 = System.currentTimeMillis();
        for(int i=0;i<times;i++){
            Flyweight flyweight = new ConcreFlyweight1(key);
        }
        Long t2 = System.currentTimeMillis();
        System.out.println("create time 1:"+(t2-t1));

        Long t3 = System.currentTimeMillis();
        for(int i=0;i<times;i++){
            FlyweightFactory.getFlyweight(key);
        }
        Long t4 = System.currentTimeMillis();
        System.out.println("create time 2:"+(t4-t3));
    }
}

输出结果:

create time 1:491
create time 2:4199

 

3.特点

优点:大大减少应用程序创建的对象,降低程序内存的占用,增强程序的性能

缺点:提高了系统复杂性;工厂类创建对象时间变长

本文地址:https://blog.csdn.net/qq_39961073/article/details/110248415

相关标签: java