您的位置:首页 > 其它

享元模式与单例模式区别

2016-07-06 16:58 633 查看
单例模式是类级别的,一个类只能有一个对象实例;

享元模式是对象级别的,可以有多个对象实例,多个变量引用同一个对象实例;

享元模式主要是为了节约内存空间,提高系统性能,而单例模式主要为了可以共享数据;

1:单例模式

public class Singleton {

    // 我来写一个单例模式  懒汉式

    private static Singleton singleton;

    private Singleton(){}

    

    public static synchronized Singleton getSingleton(){

        if(singleton==null){

            singleton=new Singleton();

        }

        return singleton;

    }

    public static void main(String[] args) {

        Singleton instance1 = Singleton.getSingleton();

        Singleton instance2 = Singleton.getSingleton();

        System.out.println(instance1==instance2);

    }

}

2:享元模式

//享元模式是多个变量公用一个对象实例  大大节约了内存空间  提高了系统性能  String类是final类型 就是使用了享元模式

//数据库连接池 线程池也是享元模式的应用

public abstract class Flyweight {

    // 享元模式 享元抽象类

    public abstract void operation();

}

//具体类 享元实现类

public class CreateFlyweight extends Flyweight {

    private String str;

    public CreateFlyweight(String str) {

        this.str = str;

    }

    @Override

    public void operation() {

        // TODO Auto-generated method stub

        System.out.println("Create---Flyweight:" + str);

    }

    public static void main(String[] args) {

        Flyweight flyweight = new CreateFlyweight("fanck");

        flyweight.operation();

    }

}

//工厂方法类 维护一个对象存储池 享元工厂类

public class FlyweightFactory {

    private Hashtable flyweights = new Hashtable();

    public FlyweightFactory() {

    };

    public Flyweight getFlyweight(Object obj) {

        Flyweight flyweight = (Flyweight) flyweights.get(obj);

        if (flyweight == null) {

            flyweight = new CreateFlyweight((String) obj);

            flyweights.put(obj, flyweight);

        }

        return flyweight;

    }

    public int getFlyweightSize() {

        System.out.println("flyweights:"+flyweights);

        return flyweights.size();

    }

    public static void main(String[] args) {

        FlyweightFactory flyweightFactory = new FlyweightFactory();

        Flyweight fly1 = flyweightFactory.getFlyweight("abc");

        Flyweight fly2 = flyweightFactory.getFlyweight("b");

        Flyweight fly3 = flyweightFactory.getFlyweight("abc");

        Flyweight fly4 = flyweightFactory.getFlyweight("ef");

        Flyweight fly5 = flyweightFactory.getFlyweight("ef");

        Flyweight fly6 = flyweightFactory.getFlyweight("ef");

        fly1.operation();

        fly2.operation();

        fly3.operation();

        fly4.operation();

        fly5.operation();

        fly6.operation();

        System.out.println(flyweightFactory.getFlyweightSize());

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: