简单工厂和抽象工厂

查看原文:http://www.ibloger.net/article/14.html


package cn.wingfly.bean;

interface Fruit {

	void eat();
}
class Orange implements Fruit{

	@Override
	public void eat() {
		System.out.println("  吃橘子    ");
	}
	
}
class Apple implements Fruit{

	@Override
	public void eat() {
		System.out.println("  吃苹果    ");
	}
	
}


/**
 * 简单工厂模式:由一个工厂对象决定创建出哪一种产品类的实例,它是工厂模式家族最简单的模式
 * 
 * 不适合对象扩展(若要创建其他水果类,必须修改工厂方法)
 * 
 * 工厂类作用:隐含式创建对象,降低代码的耦合性
 */
public class SimpleFactory {
	
	public static Fruit createFruit(String name){
		Fruit fruit = null;
		switch (name) {
			case "Orange" :
				fruit = new Orange();
				break;
			case "Apple" :
				fruit = new Apple();
				break;
			default :
				break;
		}
		return fruit;
	}
	
}


package cn.wingfly.bean;

/**
 * 抽象工厂模式:可以灵活创建未知对象,而不用修改工厂方法(不必指定产品的具体形态的情况下,创建多个产品族的对象)
 * 
 * 只能创建某一类接口类型的对象(如:只能创建水果类对象,不能创建汽车类对象)
 */
public class AbstractFactory {

	public static Fruit createFruit(String name){
		Fruit fruit = null;
		try {
			fruit = (Fruit) Class.forName(name).newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fruit;
	}
	
	public static void main(String[] args) {
		Fruit fruit = AbstractFactory.createFruit("cn.wingfly.bean.Orange");
		fruit.eat();
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值