码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式(2):工厂方法模式

时间:2018-02-15 16:34:55      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:led   trace   tis   类型   ace   一个   等等   class   决定   

工厂方法模式:

?

定义:

?

定义一个用于创建对象的接口,让子类决定实例化哪一个类。

工厂方法使用一个类的实例化延迟到子类。

?

举个栗子:我们要生产水果罐头,我们应该怎么做呢?

首先,我们须要准备好原料。其次我们须要一个罐头工厂,往工厂里运送不同的原料,出来的就是不同的罐头。

?

原料就是苹果啊、橘子啊等等的这些类。

?

interface IFruits {
	public void taste();
}

class Apple implements IFruits {

	public void taste() {
		System.out.println("I‘m apple");
	}
}

class Orange implements IFruits {

	public void taste() {
		System.out.println("I‘m orange");
	}
}


?

工厂呢就是可以生产水果罐头的工厂啊。

?

abstract class AbstractFactory {
	// 採用泛型对输入參数进行限制:
	// 1.必须是Class类型
	// 2.必须是IFruits类型的子类
	public abstract <T extends IFruits> T createCan(Class<T> c);
}

class Factory extends AbstractFactory {


	@Override
	public <T extends IFruits> T createCan(Class<T> c) {
		IFruits fruits = null;

		try {
			fruits = (IFruits) Class.forName(c.getName()).newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return (T) fruits;
	}

}


?

场景类:

?

public class Client {

	public static void main(String[] args) {
		AbstractFactory factory = new Factory();
		IFruits apple = factory.createCan(Apple.class);
		apple.taste();
		IFruits orange = factory.createCan(Orange.class);
		orange.taste();
	}
}

?

?

书中的样例:女娲造人,产生各种肤色的人。

?

package ne;

interface Human {
	public void say();
}

class Black_human implements Human {

	public void say() {
		System.out.println("I‘m black");
	}
}

class Yellow_human implements Human {

	public void say() {
		System.out.println("I‘m yellow");
	}

}

abstract class AbstractFactory {
	public abstract <T extends Human> T createHuman(Class<T> c);
}

class Factory extends AbstractFactory {

	@Override
	public <T extends Human> T createHuman(Class<T> c) {
		Human human = null;
		try {
			human = (Human) Class.forName(c.getName()).newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return (T) human;
	}
}

public class Client {
	public static void main(String[] args) {
		AbstractFactory factory = new Factory();
		Human black_human = factory.createHuman(Black_human.class);
		Human yellow_human = factory.createHuman(Yellow_human.class);
		black_human.say();
		yellow_human.say();
	}
}


?

?

?


?

设计模式(2):工厂方法模式

标签:led   trace   tis   类型   ace   一个   等等   class   决定   

原文地址:https://www.cnblogs.com/llguanli/p/8449577.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!