`
huhu_long
  • 浏览: 69076 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

简单工厂模式

阅读更多
缺点: 不符合开闭原则

工厂类
public class SimpleCarFactory {
	public static <T extends Car> T createCar(Class<T> c) {
		Car car = null;

		try {
			car = (Car) Class.forName(c.getName()).newInstance();
		} catch (Exception e) {
			// Handle exception...
		}

		return (T) car;
	}
}


客户端代码
private static void testSimpleFactory() {
	Car audi = SimpleCarFactory.createCar(Audi.class);
	audi.showDes();
	audi.start();
	audi.showCurrentSpeed();
	audi.stop();

	Car bmw = SimpleCarFactory.createCar(BMW.class);
	bmw.showDes();
	bmw.start();
	bmw.showCurrentSpeed();
	bmw.stop();

	Car benz = SimpleCarFactory.createCar(Benz.class);
	benz.showDes();
	benz.start();
	benz.showCurrentSpeed();
	benz.stop();
}


运行结果:
引用
I'm Audi
Audi started...
180
Audi stoped...
I'm BMW
BMW started...
200
BMW stoped...
I'm Benz
Benz started...
210
Benz stoped...
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics