简单工厂模式

主要目的是将对象的创建和对象的实现分离。

缺点是每次增加实现类都要修改工厂类

public interface car {//抽象接口类
	public void run();
}
public class BYD implements car//具体实现
{
	@Override
	public void run() {
		System.out.println(getClass().getName() + " run");
	}
}
public class BMW implements car//具体实现
{
	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println(getClass().getName() + " run");
	}
}
public class SimpleFactory {//简单工厂方法
	public static car createCar(String type)
	{
		if( type.equals("byd")) {
			return new BYD();
		}
		else if( type.equals("bmw")) {
			return new BMW();
		}
		else {
			return null;
		}
	}
}
public class client {//使用类
	public static void main(String[] main)
	{
		car byd = SimpleFactory.createCar("byd");
		car bmw = SimpleFactory.createCar("bmw");
		
		byd.run();
		bmw.run();
	}
}

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章