当前位置:学者斋 >

计算机 >java语言 >

java工厂的方法是什么

java工厂的方法是什么

创建新对象最简单的办法是使用new关键字和具体类。只有在某些场合下,创建和维护对象工厂所带来的额外复杂性才是物有所值。以下是小编为大家搜索整理java工厂的方法是什么,希望能给大家带来帮助!更多精彩内容请及时关注我们应届毕业生考试网!

java工厂的方法是什么

  工厂方法概述

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

优点

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

缺点

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

class IntegerDemo { public static void main(String[] args) { Factory factory = new DogFactory(); Animal animal = teAnimal(); (); factory = new CatFactory(); animal = teAnimal(); (); }}abstract class Animal {// 抽象类 public abstract void eat();}class Dog extends Animal {// 狗 public void eat() { tln("a dog is eatting."); }}class Cat extends Animal {// 猫 public void eat() { tln("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(); }}

工厂方法概述

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

优点

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

缺点

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

public class IntegerDemo { public static void main(String[] args) { Factory factory = new DogFactory(); Animal animal = teAnimal(); (); factory = new CatFactory(); animal = teAnimal(); (); }}abstract class Animal {// 抽象类 public abstract void eat();}class Dog extends Animal {// 狗 public void eat() { tln("a dog is eatting."); }}class Cat extends Animal {// 猫 public void eat() { tln("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(); }}

标签: JAVA 工厂
  • 文章版权属于文章作者所有,转载请注明 https://xuezhezhai.com/jsj/java/1qx200.html