java设计模式:工厂模式

本文详细介绍了工厂模式中的简单工厂和抽象工厂两种类型,并通过实例代码展示了如何利用这些模式创建对象,同时强调了依赖抽象原则的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工厂模式(factory pattern):即使用工厂方法来替代new的方式创建对象

工厂模式可分简单工厂和抽象工厂模式。


下面对这三种类型进行一一演示

1简单工厂模式

 1)定义超类

public abstract class Car {
    public abstract void display(); //外观
}

 2)子类

public class BMWCar extends Car {
    @Override
    public void display() {
        System.out.println("宝马车");
    }
}
public class AUTOCar extends Car {
    @Override
    public void display() {
        System.out.println("奥拓车");
    }
}

3)工厂类

public class CarFactory {
    public static Car getCar(String type) {
        if(StringUtils.isBlank(type))
            throw new RuntimeException("参数异常");
        else if("BMW".equals(type))
            return new BMWCar();
        else if("AUTO".equals(type))
            return new AUTOCar();
        return null;
    }
}

4)测试

public static void main(String[] args){
    CarFactory.getCar("BMW").display();
}


2、抽象工场模式

场景:比如现在宝马和奥拓有分中国产和德国产

1)超类

public abstract class Car {
    public abstract void display();
    public static Car getCar(IFactory iFactory,String type) {
        return iFactory.getCar(type);
    }
}

2)子类

public class CNAutoCar extends Car {
    @Override
    public void display() {
        System.out.println("中国产奥拓");
    }
}
public class CNBMWCar extends Car {
    @Override
    public void display() {
        System.out.println("中国产宝马");
    }
}
public class GMAutoCar extends Car{
    @Override
    public void display() {
        System.out.println("德国产奥拓");
    }
}
public class GMBMWCar extends Car {
    @Override
    public void display() {
        System.out.println("德国产宝马");
    }
}

3)工厂类

public class CNCarFactory implements IFactory {
    @Override
    public Car getCar(String type) {
        if(StringUtils.isBlank(type))
            throw new RuntimeException("参数异常");
        if("BMW".equals(type))
            return new CNBMWCar();
        else if("AUTO".equals(type))
            return new CNAutoCar();
        return null;
    }
}
public class GMCarFactoty implements IFactory {
    @Override
    public Car getCar(String type) {
        if(StringUtils.isBlank(type))
            throw new RuntimeException("参数异常");
        if("BMW".equals(type))
            return new GMBMWCar();
        else if("AUTO".equals(type))
            return new GMAutoCar();
        return null;
    }
}

工厂模式中(也适用于所有设计模式),需要注意有个依赖抽象原则:

1)不要让变量持有具体类的引用

2)不要让类继承具体类,要继承抽象类或者实现接口

3)不要覆盖超类中已实现的方法,如果设计的超类中已实现的方法出现被子类覆盖的情况,说明该超类设计的不合理


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值