享元模式
//享元模式
//CopyRight(C) CAnca software Office.2006
//Created by CAnca.
import java.util.*;
public class ShareMode{
public static void main(String[] args){
int number = 23;
FlyweightFactory flyweight = new FlyweightFactory();
Component com1 = flyweight.getShare("X");
com1.operation(--number);
Component com2 = flyweight.getShare("Y");
com2.operation(--number);
Component com3 = flyweight.getShare("W");
com3.operation(--number);
Component com4 = flyweight.getShare("U");
com4.operation(--number);
UnShare us = new UnShare();
us.operation(--number);
}
}
class FlyweightFactory{
private Hashtable flyweights = new Hashtable();
public FlyweightFactory(){
flyweights.put("X",new ShareA());
flyweights.put("Y",new ShareB());
flyweights.put("W",new ShareC());
flyweights.put("U",new ShareD());
}
public Component getShare(String key){
if(flyweights.containsKey(key)){
return ((Component)flyweights.get(key));
}
return null;
}
}
abstract class Component{
abstract void operation(int key);
}
class ShareA extends Component{
public void operation(int key){
System.out.println("ShareA.operation()--" + key);
}
}
class ShareB extends Component{
public void operation(int key){
System.out.println("ShareB.operation()--" + key);
}
}
class ShareC extends Component{
public void operation(int key){
System.out.println("ShareC.operation()--" + key);
}
}
class ShareD extends Component{
public void operation(int key){
System.out.println("ShareD.operation()--" + key);
}
}
class UnShare extends Component{
public void operation(int key){
System.out.println("UnShare.operation()--" + key);
}
}