工厂模式只适用于对象的创建。说白了就是封装了new‘一个对象的操作。
简单工厂模式
1. 目的
工厂模式就是专门负责将大量有共同接口的类实例化,
而且不必事先知道每次是要实例化哪一个类的模式。
它定义一个用于创建对象的接口,由子类决定实例化哪一个类。
2 . 简单工厂模式的结构
3. 一个简单例子
java 代码
- // 产品接口
- public interface Product {
- public void getName();
- }
- // 具体产品A
- public class ProductA implements Product {
- public void getName() {
- System.out.println(" I am ProductA ");
- }
- }
- // 具体产品B
- public class ProductB implements Product {
- public void getName() {
- System.out.println(" I am ProductB ");
- }
- }
- // 工厂类
- public class ProductCreator {
- public Product createProduct(String type) {
- if (" A ".equals(type)) {
- return new ProductA();
- }
- if (" B ".equals(type)) {
- return new ProductB();
- } else
- return null;
- }
- public static void main(String[] args) {
- ProductCreator creator = new ProductCreator();
- creator.createProduct(" A ").getName();
- creator.createProduct(" B ").getName();
- }
- }
1. 类的创建可以被配置。 字符串A和B都可以写在配置文件里。
2. 类的创建隐藏了new操作符。
抽象工厂模式
1. 抽象工厂模式可以说是简单工厂模式的扩展,
它们主要的区别在于需要创建对象的复杂程度上。
在抽象工厂模式中,创建对象的方法变成了接口(对应与c++的虚函数),可以让具体的创建对象的子类来实现。
2. 抽象工厂模式的结构
3. 一个简单例子
java 代码
- // 产品 Plant接口
- public interface Plant {
- }
- // 具体产品PlantA,PlantB
- public class PlantA implements Plant {
- public PlantA() {
- System.out.println(" create PlantA ! ");
- }
- public void doSomething() {
- System.out.println(" PlantA do something ");
- }
- }
- public class PlantB implements Plant {
- public PlantB() {
- System.out.println(" create PlantB ! ");
- }
- public void doSomething() {
- System.out.println(" PlantB do something ");
- }
- }
- // 产品 Fruit接口
- public interface Fruit {
- }
- // 具体产品FruitA,FruitB
- public class FruitA implements Fruit {
- public FruitA() {
- System.out.println(" create FruitA ! ");
- }
- public void doSomething() {
- System.out.println(" FruitA do something ");
- }
- }
- public class FruitB implements Fruit {
- public FruitB() {
- System.out.println(" create FruitB ! ");
- }
- public void doSomething() {
- System.out.println(" FruitB do something ");
- }
- }
- // 抽象工厂方法
- public interface AbstractFactory {
- public Plant createPlant();
- public Fruit createFruit();
- }
- // 具体工厂方法
- public class FactoryA implements AbstractFactory {
- public Plant createPlant() {
- return new PlantA();
- }
- public Fruit createFruit() {
- return new FruitA();
- }
- }
- public class FactoryB implements AbstractFactory {
- public Plant createPlant() {
- return new PlantB();
- }
- public Fruit createFruit() {
- return new FruitB();
- }
- }
任何设计模式都是服务于实际的项目的。用复杂的术语来描述的设计模式你读一万遍你
都无法理解,还不如在你实际的项目中采用。或者看现有项目的代码是如何用的。
工厂模式是很简单的,不要被复杂的名词或者是术语迷惑。