WEB开发网
开发学院WEB开发Jsp Java设计模式例子FactoryMethodPattern 阅读

Java设计模式例子FactoryMethodPattern

 2008-01-05 18:55:55 来源:WEB开发网   
核心提示://Creator.javapublic abstract class Creator{/** *looks like a factory *contains some PRodUCts and some process methods */protected Product duct;abstract String

  //Creator.java
  
  public abstract class Creator
  {
    /**
     * looks like a factory
     * contains some PRodUCts and some process methods
     */
    protected Product duct;
    abstract String processProduct();
    abstract String processProductSpecial();
    public String Operation()
    {
      return processProduct(); // FactoryMethod for implemention;
    }
  }
  
  //ConcreteProduct.java
  
  public class ConcreteProduct extends Product
  {
    public ConcreteProduct()
    {
      System.out.println("construct the ConcreteProduct object");
    }
    public String makeString(String str)
    {
      return "This is the product after processing:"+str;
    }
  }
  
  //Product.java
  public abstract class Product
  {
    public abstract String makeString(String str);
  }
  
  //ConcreteCreatorA.java
  
  public class ConcreteCreatorA extends Creator
  {
    /**
     * You can write some other class like this to override
     * the same methods do diffrent thing;
     */
    public ConcreteCreatorA()
    {
      duct=new ConcreteProduct();
      System.out.println("instanced a product");
  
    }
    public String processProduct()
    {
      System.out.println("product A:");
      return duct.makeString("Make @#a product");
  
    }
    public String processProductSpecial()
    {
      System.out.println("special product B:");
      //add another method here
      return duct.makeString("Make Special @#B product");
    }
  }
  
  //TestFactoryMethod.java
  public class TestFactoryMethod
  {
    public TestFactoryMethod()
    {
    }
    public static void main(String[] arg)
    {
      ConcreteCreatorA cc=new ConcreteCreatorA();
      System.out.println(cc.Operation());
      System.out.println(cc.processProductSpecial());
    }
  }

Tags:Java 设计模式 例子

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接