下一篇:设计模式(二)——抽象工厂模式

一、概述

官方解释:Define an interface for creating an object,but let subclass decide which class to instantiate.Factory Method lets a class defer instantiation to subclass.(定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法是一个类的实例化延迟到其子类。)
我的理解:工厂模式,在某个类(工厂类)的某个方法(工厂方法)中,根据形参确定运行时类型,新建对象并返回(return)。

参与者:产品类(抽象产品类AbstractProduct、具体产品类ConcreteProduct)、具体工厂类ConcreteFactory

类图:

设计模式(一)——工厂模式_# (0)设计模式

 

二、代码(FruitFactory)

FruitFactory类图:

设计模式(一)——工厂模式_# (0)设计模式_02

 

代码示意:



interface Fruit{
	void display();
}
class Apple implements Fruit{

	@Override
	public void display() {
		// TODO Auto-generated method stub
		System.out.println("This is an Apple");
	}
	
}
class Orange implements Fruit{

	@Override
	public void display() {
		System.out.println("This is an orange");
		
	}
	
}
class Banana implements Fruit{

	@Override
	public void display() {
		// TODO Auto-generated method stub
		System.out.println("This is a banana");
	}
	
}
class FruitFactory {
	public Fruit produce_Fruit(String type){
		//工厂模式的精髓在于   工厂类的工厂方法中根据参数 ,新建不同工厂产品,   其中运用到多态
		if (type.equalsIgnoreCase("apple")) {
			return new Apple();
		}
		if (type.equalsIgnoreCase("orange")) {
			return new Orange();
		}
		if (type.equalsIgnoreCase("banana")) {
			return new Banana();
		}
		return null;
	}
}
public class TestFactory {

	public static void main(String[] args) {
		FruitFactory factory=new FruitFactory();
		factory.produce_Fruit("apple").display();
		factory.produce_Fruit("orange").display();
		factory.produce_Fruit("banana").display();
	}

}

输出结果:

This is an Apple
This is an orange
This is a banana

 

三、小结

       工厂模式的精髓在于:工厂类的工厂方法中根据参数 ,使用向上转型新建不同工厂产品,而不需要单独新建每一个类

 

下一篇:设计模式(二)——抽象工厂模式