Factory

 
public interface Animal {
/**所有动物都会吃*/
 public void eat();
}
public class Tiger implements Animal {
 public void eat() {
  System.out.println("老虎要吃饭!");
 }
 public void run() {
  System.out.println("老虎要跑步!");
 }
}
public class Parrot implements Animal {
 public void eat() {
  // TODO Auto-generated method stub
  System.out.println("鹦鹉要吃饭");
 }
 public void fly() {
  System.out.println("鹦鹉要飞翔");
 }
 
public interface Factory {
 /** 工厂类 */
 public Animal createAnimal();
}
public class TigerFactory implements Factory {
 public Animal createAnimal() {
  // TODO Auto-generated method stub
  return new Tiger();
 }
}
 
public class DolphinFactory implements Factory {
 public Animal createAnimal() {
  // TODO Auto-generated method stub
  return new Dolphin();
 }
}
 
public class ParrotFactory implements Factory {
 public Animal createAnimal() {
  // TODO Auto-generated method stub
  return new Parrot();
 }
}
public class Client {
 /**
  * @param args
  * @throws IllegalAccessException
  * @throws InstantiationException
  * @throws ClassNotFoundException
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Factory factory = new TigerFactory();
  Animal animal = factory.createAnimal();
  animal.eat();
  factory = new DolphinFactory();
  animal = factory.createAnimal();
  animal.eat();
  factory = new ParrotFactory();
  animal = factory.createAnimal();
  animal.eat();
 }
}
定义:工厂方法模式中抽象工厂类负责定义创建对象接口,具体对象的创建工作由实现该抽象工厂的具体类实现;
原理:工厂方法模式由四部分组成:抽象工厂类,实现抽象工厂类的具体方法,抽象类,实现抽象类的具体方法;
优点:1、客户端不负责对象的创建,而把这个任务交给了具体的工厂类;2、新产品加进来,只需要新增一个具体的创建产品的工厂类;
缺点:使用该模式需要额外地编写代码,增加了工作量。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值