java 工厂方法详解及实例代码
更新时间:2017年01月25日 09:45:10 投稿:lqh
这篇文章主要介绍了java 工厂方法详解及实例代码的相关资料,需要的朋友可以参考下
工厂方法概述
工厂方法模式中抽象工厂类负责定义创建对象的接口,具体对象的创建工作由继承抽象工厂的具体类实现。
优点
客户端不需要在负责对象的创建,从而明确了各个类的职责,如果有新的对象增加,只需要增加一个具体的类和具体的工厂类即可,不影响已有的代码,后期维护容易,增强了系统的扩展性
缺点
需要额外的编写代码,增加子工作量
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();
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
相关文章
全面解析JPA 仓库repository中的findAll()方法
这篇文章主要介绍了全面解析JPA 仓库repository中的findAll()方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-02-02
Spring @Transactional事务失效的原因分析
一个程序中不可能没有事务,Spring中,事务的实现方式分为两种:编程式事务和声明式事务。日常项目中,我们都会使用声明式事务 @Transactional来实现事务,本文来和大家聊聊什么情况会导致@Transactional事务失效2022-09-09
SpringBoot集成本地缓存性能之王Caffeine示例详解
这篇文章主要为大家介绍了SpringBoot集成本地缓存性能之王Caffeine的示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-07-07


最新评论