设计模式之简单工厂模式

简单工厂模式属于创建型模式,又叫静态工厂方法模式。通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。


该模式主要包含的角色有:工厂角色,抽象角色,具体产品角色。以下的几个类就是一个简单工厂模式的示例。


1.抽象接口或父类

public interface Fruit {

	/*
	 * 获取方法
	 */
	public void get();
}
2. 具体实现类

具体实现类1:

public class Apple implements Fruit {

	@Override
	public void get() {
		System.out.println("采集小苹果");
	}

}

具体实现类2:

public class Banana implements Fruit {

	@Override
	public void get() {
		System.out.println("采集香蕉");
	}

}

3. 简单工厂类

public class FruitFactory {

	/*
	 * 简单工厂模式方式一
	 */
	public static Fruit getFruit(String type) throws InstantiationException, IllegalAccessException {
		if(type.equalsIgnoreCase("apple")) {
			return Apple.class.newInstance();
		} else if(type.equalsIgnoreCase("banana")) {
			return Banana.class.newInstance();
		} else {
			System.out.println("没有找到相应的类型");
			return null;
		}
	}
	
	/*
	 * 简单工厂模式方式二
	 */
	public static Fruit getFruit2(String type) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		@SuppressWarnings("rawtypes")
		Class clazz = Class.forName(type);
		return (Fruit) clazz.newInstance();
	}
}

使用JUnit测试简单工厂方法类:

public class TestSimpleFactory {

	@Test
	public void test() throws InstantiationException, IllegalAccessException {
		Fruit apple = FruitFactory.getFruit("apple");
		Fruit banana = FruitFactory.getFruit("banana");
		apple.get();
		banana.get();
	}
	
	@Test
	public void test2() throws InstantiationException, IllegalAccessException {
		Fruit apple = FruitFactory.getFruit("Apple");
		Fruit banana = FruitFactory.getFruit("Banana");
		apple.get();
		banana.get();
	}
}

以上几个类就显示简单工厂模式的使用方法,总的来说简单工厂方法就是通过一个工厂类根据具体对象类名去获得实例对象。





个人微信公众号:programmlife,如有兴趣敬请关注,主要表达了一个码农的所见所思所叹,也可扫描下方二维码关注:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值