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

简单工厂模式

时间:2015-02-24 09:09:46      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:工厂模式   设计模式   

以水果为例讲解简单工厂模式,其中有三种水果,

*葡萄 Grape

*草莓Strawberry

*苹果Apple

水果并无具体的对象,因此是一个各个水果都适用的接口,以便与其他植物分隔开来。

技术分享

三种水果均有自己不同的属性,现在实现水果接口及其三种水果的源码。

Fruit:

package SimpleFactory;

public interface Fruit {
	
	/**
	 * 生长
	 */
	void grow();
	
	/**
	 * 收获
	 */
	void harvest();
	
	/**
	 * 种植
	 */
	void plant();
}
Apple:

package SimpleFactory;

public class Apple implements Fruit {
	private int treeAge;	//苹果树的树龄
	@Override
	public void grow() {
		log("Apple is growing");
	}

	@Override
	public void harvest() {
		log("Apple has been harvested");
	}

	@Override
	public void plant() {
		log("Apple has been planted");
	}

	public int getTreeAge() {
		return treeAge;
	}

	public void setTreeAge(int treeAge) {
		this.treeAge = treeAge;
	}

	private void log(String msg){
		System.err.println(msg);
	}
}
Grape:

package SimpleFactory;

public class Grape implements Fruit {
	private boolean seedless;	//葡萄有籽或者无籽
	@Override
	public void grow() {
		log("Grape is growing...");
	}

	@Override
	public void harvest() {
		log("Grape has been harvested");
	}

	@Override
	public void plant() {
		log("Grape has been planted");
	}

	private void log(String msg){
		System.err.println(msg);
	}

	public boolean isSeedless() {
		return seedless;
	}

	public void setSeedless(boolean seedless) {
		this.seedless = seedless;
	}
}
Strawberry:

package SimpleFactory;

public class Strawberry implements Fruit {

	@Override
	public void grow() {
		log("Strawberry is growing...");
	}

	@Override
	public void harvest() {
		log("Strawberry has been harvested.");
	}

	@Override
	public void plant() {
		log("Strawberry has been planted");
	}

	private void log(String msg){
		System.err.println(msg);
	}
}

实现这三种水果后,还需要一个园丁来照料他们,因此还有一个园丁类,源码为:

package SimpleFactory;

public class FruitGardener {
	
	/**
	 * 静态工厂方法
	 * @param which
	 * @return
	 */
	public static Fruit factory(String which)throws BadFruitException{
		if(which.equalsIgnoreCase("apple")){
			return new Apple();
		}else if(which.equalsIgnoreCase("strawberry")){
			return new Strawberry();
		}else if(which.equalsIgnoreCase("grape")){
			return new Grape();
		}else{
			throw new BadFruitException("Bad fruit request");
		}
		
	}
}
里面有一个BadException,当出现在园子中没有出现的水果时,要抛出异常,因此还有一个异常类。

BadException:

package SimpleFactory;

public class BadFruitException extends Exception {

	public BadFruitException(String msg){
		super(msg);
	}
}
当这些都实现后,便可使用此模式进行收获,源码为:

package SimpleFactory;

public class Client {
	public static void main(String[] args) {
		try {
			FruitGardener.factory("grape");
			FruitGardener.factory("apple");
			FruitGardener.factory("strawberry");
		} catch (BadFruitException e) {
		}
	}
}

如此,便实现简单的工厂模式。




简单工厂模式

标签:工厂模式   设计模式   

原文地址:http://blog.csdn.net/u012734441/article/details/43917211

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