当前位置: 移动技术网 > IT编程>开发语言>Java > java 工厂方法详解及实例代码

java 工厂方法详解及实例代码

2019年07月22日  | 移动技术网IT编程  | 我要评论

工厂方法概述

工厂方法模式中抽象工厂类负责定义创建对象的接口,具体对象的创建工作由继承抽象工厂的具体类实现。

优点

客户端不需要在负责对象的创建,从而明确了各个类的职责,如果有新的对象增加,只需要增加一个具体的类和具体的工厂类即可,不影响已有的代码,后期维护容易,增强了系统的扩展性

 缺点

需要额外的编写代码,增加子工作量

public class integerdemo {
  public static void main(string[] args) {
    factory factory = new dogfactory();
    animal animal = factory.createanimal();
    animal.eat();
 
    factory = new catfactory();
    animal = factory.createanimal();
    animal.eat();
  }
}
 
abstract class animal {// 抽象类
  public abstract void eat();
}
 
class dog extends animal {// 狗
  public void eat() {
    system.out.println("a dog is eatting.");
  }
}
 
class cat extends animal {// 猫
  public void eat() {
    system.out.println("a cat is eatting.");
  }
}
 
interface factory {// 接口
  public abstract animal createanimal();
}
 
class dogfactory implements factory {// 实现接口
  public animal createanimal() {
    return new dog();
  }
}
 
class catfactory implements factory {// 实现接口
  public animal createanimal() {
    return new cat();
  }
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网