介绍
简单工厂模式
简单工厂都有哪几个角色:
- 抽象产品(Car)
- 具体产品(WuLingCar,DaZhongCar)
- 具体工厂(CarFactory )
- 产品使用者(SimplenessFactory )
package factory;public class SimplenessFactory {public static void main(String[] args) {Car wuling = CarFactory.getCar("wuling");wuling.wheel();Car dazhong = CarFactory.getCar("dazhong");dazhong.wheel();}
}interface Car {void wheel();
}class WuLingCar implements Car {@Overridepublic void wheel() {System.out.println("五菱车装轮子");}
}class DaZhongCar implements Car {@Overridepublic void wheel() {System.out.println("大众车装轮子");}
}class CarFactory {public static Car getCar(String name) {if (name == null) {return null;}if (name.equals("dazhong")) {return new DaZhongCar();} else if (name.equals("wuling")) {return new WuLingCar();}return null;}
}
工厂方法模式
工厂方法模式都有哪几个角色:
- 抽象产品(Car)
- 具体产品(WuLingCar,DaZhongCar)
- 抽象工厂(CarFactory )
- 具体工厂(WuLingFactory,DaZhongFactory)
- 产品使用者(SimplenessFactory )
package factory;public class SimplenessFactory {public static void main(String[] args) {Car wuling = new WuLingFactory().getCar();Car dazhong = new DaZhongFactory().getCar();wuling.wheel();dazhong.wheel();}
}interface Car {void wheel();
}class WuLingCar implements Car {@Overridepublic void wheel() {System.out.println("五菱车装轮子");}
}class DaZhongCar implements Car {@Overridepublic void wheel() {System.out.println("大众车装轮子");}
}interface CarFactory {Car getCar();
}class WuLingFactory implements CarFactory {@Overridepublic Car getCar() {return new WuLingCar();}
}class DaZhongFactory implements CarFactory {@Overridepublic Car getCar() {return new DaZhongCar();}
}
结论
本文链接:https://my.lmcjl.com/post/8648.html
展开阅读全文
4 评论