工厂模式介绍
工厂模式在面对对象编程中,顾名思义说的是把一个一个对象,像工厂一样生产出来,不用在像以前一样创建一个对象需要很多繁琐的步骤,也就是对对象的创建的一种封装,用很简单的方式,调用相应的方法就可以创建对象。
工厂模式的UML类图
工厂模式的主要组成成员
- 抽象工厂,其为工厂模式的核心
- 具体工厂,其实现了具体的业务逻辑
- 抽象产品,是工厂模式所创建产品父类
- 具体产品,为实现抽象产品的某个具体产品对象。
抽象工厂
抽象工厂可以写成一个接口,写出相应的方法,返回的是产品就可以,然后用具体的工厂类去继承抽象工厂接口,实现相应的抽象生产方法。
具体工厂
具体工厂是用来继承抽象工厂接口,实现生产方法,在具体实现方法中又可以用判断语句产生一个品牌下不同的商品。
抽象产品
抽象产品是用来概括所有产品共有特性,以及产品共有的方法。
具体产品
具体产品是用来继承抽象产品类,获得共有属性,同时也可以在此基础上添加特有属性,后面视线中用来创建产品用的。
工厂模式案例演示
这里用到的现实中的东西纯属举例,并无他用
案例需求
此案例需要实现两个不同品牌的工厂,分别产出自己不同牌子的电脑。
建立抽象工厂
建立抽象工厂,写出抽象生产方法
public interface ComputerFactory {
//这里抽象方法中的choose,是为了后面选取同一品牌中不同商品准备的
public ComputerProduct getComputer(int choose);
}
建立抽象商品类
构建抽象商品标准类,并写下所有商品共有方法
public abstract class ComputerProduct {
private String name;
private String type;
private int memory;
//todo 创建无参构造
public ComputerProduct() {
}
//todo 创建有参构造
public ComputerProduct(String name, String type, int memory) {
this.name = name;
this.type = type;
this.memory = memory;
}
//todo 创建get、set方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getMemory() {
return memory;
}
public void setMemory(int memory) {
this.memory = memory;
}
// TODO: 创建电脑产品抽象方法
//todo 创建产品功能方法
public abstract void function();
//todo 创建产品详情展示
public abstract void showComputer();
}
创建具体商品类
创建具体商品类,用来创建商品
创建游戏本类
public class PlayComputer extends ComputerProduct {
public PlayComputer() {
}
public PlayComputer(String name, String type, int memory) {
super(name, type, memory);
}
@Override
public void function() {
System.out.println("用来打游戏等,性能非常好");
}
@Override
public void showComputer() {
System.out.println("cpu:i7"+"\t"+"显卡:性能高"+"\t"+"价格:7799元");
}
}
创建商务本类
public class WordComputer extends ComputerProduct {
public WordComputer() {
}
public WordComputer(String name, String type, int memory) {
super(name, type, memory);
}
@Override
public void function() {
System.out.println("电脑性能一般,适合办公");
}
@Override
public void showComputer() {
System.out.println("cpu: i5"+"\t"+"显卡:一般"+"\t"+"价格:5999元");
}
}
建立具体工厂
按照不同品牌构建不同的工厂
构建第一个牌子的工厂
public class LianXiang implements ComputerFactory {
@Override
public ComputerProduct getComputer(int choose) {
if(choose == 1){
return new PlayComputer("拯救者","联想",32);
}else if(choose == 2){
return new WordComputer("tinkPad","联想",8);
}else {
return new PlayComputer("拯救者","联想",32);
}
}
}
构建第二个牌子的工厂
public class Hp implements ComputerFactory {
@Override
public ComputerProduct getComputer(int choose) {
if(choose == 1){
return new PlayComputer("暗影精灵","惠普",32);
}else if(choose == 2){
return new WordComputer("小欧14s","惠普",8);
}else {
return new PlayComputer("暗影精灵","惠普",32);
}
}
}
创建测试类
public class Test {
public static void main(String[] args) {
LianXiang lx=new LianXiang();
Hp hp=new Hp();
//创建一个联想游戏笔记本对象
ComputerProduct c1=lx.getComputer(1);
//创建一个惠普商务本对象
ComputerProduct h1 = hp.getComputer(2);
c1.showComputer();
h1.showComputer();
}
}