点击这里给我发消息 点击这里给我发消息

Java设计模式例子 FactoryMethod Pattern

添加时间:2013-12-7
    相关阅读: 设计

  //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());
    }
  }
咨询热线:020-85648757 85648755 85648616 0755-27912581 客服:020-85648756 0755-27912581 业务传真:020-32579052
广州市网景网络科技有限公司 Copyright◎2003-2008 Veelink.com. All Rights Reserved.
广州商务地址:广东省广州市黄埔大道中203号(海景园区)海景花园C栋501室
= 深圳商务地址:深圳市宝源路华丰宝源大厦606
研发中心:广东广州市天河软件园海景园区 粤ICP备05103322号 工商注册