下面來個實例,大家應該就明白了。
package flyweight;
public interface Flyweight {
void operate();
}
package flyweight;
public class FlyweightA implements Flyweight {
@Override
public void operate() {
// TODO Auto-generated method stub
System.out.println("操作---A");
}
}
package flyweight;
public class FlyweightB implements Flyweight {
@Override
public void operate() {
// TODO Auto-generated method stub
System.out.println("操作---B");
}
}
package flyweight;
public class UnsharedFlyweight implements Flyweight {
@Override
public void operate() {
// TODO Auto-generated method stub
System.out.println("非共享類操作");
}
}
package flyweight;
import java.util.HashMap;
import java.util.Map;
public class FlyweightFactory {
private Map<String, Flyweight> map=new HashMap<>();
public FlyweightFactory() {
map.put("A", new FlyweightA());
map.put("B", new FlyweightB());
}
public Flyweight getFlyweight(String key) {
return map.get(key);
}
}
package flyweight;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
FlyweightFactory flyweightFactory=new FlyweightFactory();
Flyweight flyweightA = flyweightFactory.getFlyweight("A");
Flyweight flyweightB = flyweightFactory.getFlyweight("B");
Flyweight unsharedFlyweight=new UnsharedFlyweight();
flyweightA.operate();
flyweightB.operate();
unsharedFlyweight.operate();
}
}
在實際應用中,數據庫連接池,線程池都有應用享元模式。