Java设计模式—工厂设计模式
工厂设计模式(减少耦合。通过接口或者工厂类来实现)
耦合性:粘度强(依耐性) Person p = new Person(); //耦合性强
Man p = new Person(); //耦合性弱,Man是接口或其它,Person实现这个接口
简单工厂模式是有一个工厂对象决定创建哪一种产品类的实例。
简单工厂模式是工厂模式家族中最简单有用的模式.以下给出演示样例代码:
/**
* 简单工厂设计模式
* @author Admin
*
*/
public class FactoryDesign {
public static void main(String[] args) {
Car car1 = Factory.getCar("small"); //通过接口来接收对象减少依赖度(耦合性)
Car car2 = Factory.getCar("big");
if(car1!=null){
car1.run();
}
if(car2!=null){
car2.run();
}
}
}
class Factory{ //工厂类,来间接控制生产对象
public static Car getCar(String name){
if(name.equals("small")){
return new smallCar(); //生产小汽车
}else if(name.equals("big")){
return new bigCar(); // 生产大汽车
}else return null;
}
}
interface Car{
public void run();
}
class smallCar implements Car{
@Override
public void run() {
System.out.println("小汽车在跑");
}
}
class bigCar implements Car{
@Override
public void run() {
System.out.println("大汽车在跑");
}
}
浙公网安备 33010602011771号