简单工厂模式

/** 
 * @function 
 * @version 2015年1月29日 下午7:30:12
 */
public class Main {
	public static void main(String[]args){
		try {
			//直接跟工厂要一个苹果,工厂就给你造一个苹果
			Fruit apple = FruitFactory.createFruit("apple");
			apple.getSelf();//查看下水果都有的属性
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


/**
 * 模拟产品特性
 * 水果
 * @author tj
 *
 */
interface Fruit{
	void getSelf();//模拟个产品的特性,例如获取自身的名字
}
/**
 * 水果工厂
 * @author tj
 *
 */
class FruitFactory{
	//生产水果的方法
	public static Fruit createFruit(String fruit) throws Exception{
		if(fruit.equalsIgnoreCase("apple"))
			return new Apple();
		else if(fruit.equalsIgnoreCase("pear"))
			return new Pear();
		else
			 throw new Exception();
	}
}
//实例水果,
class Pear implements Fruit{

	@Override
	public void getSelf() {
		// TODO Auto-generated method stub
		System.out.println(this.getClass().getName());
	}
	
}
//实例水果
class Apple implements Fruit{

	@Override
	public void getSelf() {
		System.out.println(this.getClass().getName());
	}
	
}

考虑设计模式的之前

应该先考虑简单工厂模式能解决什么问题

毕竟应该是先有问题 后有解决方案 然后就是出现简单工厂模式这种设计模式

简单工厂模式能解决的问题 目前理解是 可以将类的实例化延迟 

贴代码


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值