工厂模式(即创建对象的工厂)
- 简单工厂模式(也叫静态工厂模式)
- 工厂方法模式
- 抽象工厂模式
简单工厂模式
简单工厂模式类图:
示例UML类:
示例实现:
package com.kkb.dp.factory.simple;
/**
* 汽车父类
* @date 2021年4月14日
* @describe
*/
public abstract class Car {
public abstract String getName();
}
package com.kkb.dp.factory.simple;
/**
* @date 2021年4月14日
* @describe 汽车子类
*/
public class Benz extends Car{
public String getName() {
return "奔驰汽车";
}
}
package com.kkb.dp.factory.simple;
/**
* @date 2021年4月14日
* @describe 汽车子类
*/
public class BMW extends Car{
public String getName() {
return "宝马汽车";
}
}
package com.kkb.dp.factory.simple;
/**
* @date 2021年4月14日
* @describe 常量类
*/
public class Constant {
public static final String CAR_BENZ = "Benz";
public static final String CAR_BMW = "BMW";
}
package com.kkb.dp.factory.simple;
/**
* 简单工厂(静态工厂)
* @date 2021年4月14日
* @describe
*/
public class SimpleCarFactory {
public static Car createCar(String name) {
//传入Benz
if(Constant.CAR_BENZ.equals(name)) {
return new Benz();
}
//传入BMW
if(Constant.CAR_BMW.equals(name)) {
return new BMW();
}
return null;
}
}
package com.kkb.dp.factory.simple;
/**
* 简单工厂模式是实现测试类
* @date 2021年4月14日
* @describe
*/
public class TestCar {
public static void main(String[] args) {
//利用常量类来定义不容易写错
Car c1 = SimpleCarFactory.createCar(Constant.CAR_BENZ);
System.out.println(c1.getName());
Car c2 = SimpleCarFactory.createCar(Constant.CAR_BMW);
System.out.println(c2.getName());
}
}
测试类运行结果:
奔驰汽车
宝马汽车