享元模式

canca17年前 (2007-03-26)设计模式312

//享元模式
//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);
 }
}

相关文章

抽象工厂模式

//抽象工厂模式//Copyright CAnca Software office//Created by CAnca.2006public class AbstractFactory{ p...

单例模式

//CopyRight CAnca Software Office. 2006//Created by CAnca. import java.util.*; public class singleto...

工厂方法模式

//工厂方法模式:现实例子//CopyRight(C)CAnca Software Office. 2006//Created by CAnca. import java.util.*; public...

原型模式

//原型模式//CopyRight(C) CAnca Software Office.2006//Created by CAnca. public class PrototypeMode{ ...

代理模式

//代理模式--真实例子//CopyRight(C)CAnca Software Office.2006//Created by CAnca.   public class ProxyMod...

桥接模式

//桥接模式//CopyRight(C) CAnca Software Office 2006.//Created by CAnca. import java.util.*; public class...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。