工厂模式的好处就是将创建对象与使用对象解耦,使用对象的时候不需要知道对象如何创建
举一个例子,今天小明要开车出去玩,车库里面有奔驰、宝马、奥迪等等。
常用写法是
if(奔驰){
Car car=new BenChi();
}else if(宝马){
Car car=new BaoMa();
}else if(奥迪){
Car car=new AoDi();
}......
car.drive()....
这样写完全是把创建对象与使用对象放在一起,我期望的是只提供给你车型,你给我返回对象。
- // 换用简单工厂模式实现案例
- public class hacker_01_Factory {
-
- public static Car getCar(String type){
- Car car=null;
- if("BenChi".equals(type)){
- car=new BenChi();
- }else if("BaoMa".equals(type)){
- car=new BaoMa();
- }else if("AoDi".equals(type)){
- car=new AoDi();
- }
- return car;
- }
- }
-
-
- public class XiaoMing {
-
- public static void main(String[] args) {
- hacker_01_Factory.getCar("AoDi").drive();
- }
- }
-
工厂模式常用有简单工厂模式、工厂方法模式
上面简单工厂模式实现案例中对象的创建可以进行优化处理,基于懒汉延迟加载创建对象
- public class hacker_01_Factory {
-
- public static Car getCar(String type){
- Car car=null;
- if("BenChi".equals(type)){
- car=BenChi.getInstance();
- }else if("BaoMa".equals(type)){
- car=BaoMa.getInstance();
- }else if("AoDi".equals(type)){
- car=AoDi.getInstance();
- }
- return car;
- }
-
- public static class AoDi implements Car{
- public static class AoDiHolder{
- public final static AoDi INSTANCE=new AoDi();
- }
- public static AoDi getInstance(){
- return AoDiHolder.INSTANCE;
- }
- @Override
- public void drive() {
- System.out.println("AoDi");
- }
- }
-
- public static class BaoMa implements Car{
- public static class BaoMaHolder{
- public final static BaoMa INSTANCE=new BaoMa();
- }
- public static BaoMa getInstance(){
- return BaoMaHolder.INSTANCE;
- }
- @Override
- public void drive() {
- System.out.println("BaoMa");
- }
-
-
- }
-
- public static class BenChi implements Car{
- public static class BenChiHolder{
- public final static BenChi INSTANCE=new BenChi();
- }
- public static BenChi getInstance(){
- return BenChiHolder.INSTANCE;
- }
- @Override
- public void drive() {
- System.out.println("BenChi");
- }
-
- }
-
- }
总结,业务场景中如果涉及到分支判断创建不同对象,可以加一层Factory工厂,这样如果后面添加保时捷对象的时候就不需要改大量的分支判断,只需要修改Factory工厂判断。