熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java高級技術 >> 正文

Java設計模式例子 FactoryMethod Pattern

2022-06-13   來源: Java高級技術 

  //Creatorjava
  
  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;
    }
  }
  
  //ConcreteProductjava
  
  public class ConcreteProduct extends Product
  {
    public ConcreteProduct()
    {
      Systemoutprintln(construct the ConcreteProduct object);
    }
    public String makeString(String str)
    {
      return This is the product after processing:+str;
    }
  }
  
  //Productjava
  public abstract class Product
  {
    public abstract String makeString(String str);
  }
  
  //ConcreteCreatorAjava
  
  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();
      Systemoutprintln(instanced a product);
  
    }
    public String processProduct()
    {
      Systemoutprintln(product A:);
      return ductmakeString(Make @#a product);
  
    }
    public String processProductSpecial()
    {
      Systemoutprintln(special product B:);
      //add another method here
      return ductmakeString(Make Special @#B product);
    }
  }
  
  //TestFactoryMethodjava
  public class TestFactoryMethod
  {
    public TestFactoryMethod()
    {
    }
    public static void main(String[] arg)
    {
      ConcreteCreatorA cc=new ConcreteCreatorA();
      Systemoutprintln(ccOperation());
      Systemoutprintln(ccprocessProductSpecial());
    }
  }
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27358.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.