设计模式--享元模式(Flyweight pattern)

享元模式也被称作“轻量级模式”。

享元模式的主要目的是减少系统中重复对象的数量,在一定程度上降低内存消耗,提高系统运行速度。

当系统中需要创建多个对象,且这些对象可以在同一时间被多个线程共享的时候,可以考虑使用享元模式。

 

享元模式的典型应用如下所示:

 设计模式--享元模式(Flyweight pattern)_第1张图片

 

代码如下:

 

package com.kingswood.pattern.creational.flyweight; import java.util.HashMap; import java.util.Map; public class FlyweightFactory { private static FlyweightFactory S_INSTANCE = new FlyweightFactory(); private static Map flyweightsPool = new HashMap(); public static FlyweightFactory getInstance(){ return S_INSTANCE; } public Flyweight getFlyweight(String a, String b){ Flyweight flyweight = null; if(flyweightsPool.get(a+b) == null){ flyweight = new Flyweight(a ,b); flyweightsPool.put((a+b), flyweight); }else{ flyweight = (Flyweight)flyweightsPool.get(a+b); } return flyweight; } }


package com.kingswood.pattern.creational.flyweight; public class Flyweight { private String a; private String b; public Flyweight(String a, String b){ this.a = a; this.b = b; } public String getA() { return a; } public void setA(String a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; } }

 

package com.kingswood.pattern.creational.flyweight; import junit.framework.TestCase; public class Client extends TestCase { public void testMethod(){ FlyweightFactory factory = FlyweightFactory.getInstance(); Flyweight f1 = factory.getFlyweight("aaa", "bbb"); Flyweight f2 = factory.getFlyweight("aaa", "bbb"); assertSame(f1, f2); } }

你可能感兴趣的:(设计模式--享元模式(Flyweight pattern))