享元模式
package ink.yql.flyweight;
public interface Flyweight {
String say();
}
package ink.yql.flyweight;
public class FlyweightImpl01 implements Flyweight{
private String name;
@Override
public String say() {
return name;
}
public FlyweightImpl01(String name){
this.name = name;
}
}
package ink.yql.flyweight;
import java.util.HashMap;
import java.util.Map;
public class FlyweihtFactory {
private static Map<String, Flyweight> map = new HashMap<>();
static Flyweight getInstance(String name){
Flyweight flyweight = map.get(name);
if (flyweight == null){
FlyweightImpl01 flyweightImpl01 = new FlyweightImpl01(name);
map.put(name,flyweightImpl01);
return flyweightImpl01;
}
return flyweight;
}
}
测试
package ink.yql.flyweight;
import ink.yql.factory02.FlipPhoneFactory;
public class Test01 {
public static void main(String[] args) {
Flyweight a1 = FlyweihtFactory.getInstance("a");
Flyweight a2 = FlyweihtFactory.getInstance("a");
Flyweight a3 = FlyweihtFactory.getInstance("a3");
Flyweight b = FlyweihtFactory.getInstance("b");
System.out.println(a1);
System.out.println(a2);
System.out.println(a3);
System.out.println(b);
}
}