静态工厂模式、
class Test5
{
public static void main(String[] args)
{
Car c=CarFactory.getCarInstance(Bmw.BMWID);
}
}
interface Car
{
public void run();
}
class CarFactory
{
//静态工厂方法 好处,可以根据需求获得对应的对象,不用自己在去创建对象
public static Car getCarInstance(int carId){
if(carId==Bmw.BMWID)
{
return new Bmw();
}
else if(carid==Benz.BENZID)
{
return new Benz();
}else{
return null;
}
}
}
class Bmw implements Car
{
public static final int BMWID=1;
public void run(){
System.out.println("bmw run...");
}
}
class Benz implements Car
{
public static final int BENZID=2;
public void run(){
System.out.println("Benz run...");
}
}
|