`
galo
  • 浏览: 36687 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

java设计模式(工厂方法模式)

阅读更多
  工厂方法模式(Factory Method):
  定义一个创建产品对象的工厂类,由该工厂统一创建继承了同一个接口的多个产品对象。
  根据创建策略的不同,又分为3种类型。
  ->工厂方法模式:为普通的工厂方法模式。
  ->多个工厂方法模式:提供了多个工厂方法,分别创建不同的产品对象.
  ->静态工厂方法模式:工厂方法是静态的,不需要实例化工厂即可创建产品对象。

代码分析:
  ●定义接口
public interface Animal{

  public int sale();
}


  ●定义三个具体实现类(数目随意)
 
//养猪
public class Pig implements Animal{

  int price = 10;//价格
  int weight = 200;//重量
  public int sale(){

    return price * weight;
  }
}
//养鸡
public class Chicken implements Animal{

  int price = 5;//价格
  int weight = 20;//重量
  int egg = 20;//鸡蛋
  public int sale(){

    return price * weight + egg;
  }
}
//养羊
public class Sheep implements Animal{
int price = 10;//价格
int weight = 100;//重量
int wool = 50;//羊毛
public int sale(){

  return price * weight + wool;
}
}


  ●工厂方法模式 类
  public class Farm1{

    public Animal produce(String type){
      
      if("pig".equals(type)){return new Pig();}
      else if("chicken".equals(type)){return new Chicken();}
      else{return new Sheep();}
    }
  }



  ●多个工厂方法模式 类
public class Farm2{

  public Animal producePig(){return new Pig();}
  public Animal produceChicken(){return new Chicken();}
  public Animal produceSheep(){return new Sheep();}
}


  ●静态工厂方法模式 类
public class Farm3{

  public static Animal producePig(){return new Pig();}
  public static Animal produceChicken(){return new Chicken();}
  public static Animal produceSheep(){return new Sheep();}
}


省略测试代码,写得累啊
  ●何时使用工厂方法模式
  工厂方法模式的核心是工厂类,这个类包含了创建产品的决策策略,它可以决定如何和何时创建什么产品对象。
  工厂方法模式应用场景:凡是出现了大量的产品需要创建,并且具有共同的接口时,可以通过工厂方法模式进行创建。

java中的应用有:Swing中的静态工厂类BorderFactory.
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics