簡單工廠模式

主要目的是將對象的創建和對象的實現分離。

缺點是每次增加實現類都要修改工廠類

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();
	}
}

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