每日一题 为了工作 2020 0419 第四十八题

// 简单工厂设计模式

  • 工厂设计模式提供了接口而不是实现的代码方法。
  • 工厂模式从客户端代码中删除实际实现类的实例化。工厂模式使我们的代码更健壮,耦合更少,易于扩展。
  • 工厂模式通过继承提供实现和客户端类之间的抽象。
package com.swust.modle.factory;
/**
 *
 * @author 雪瞳
 * @Slogan 静水潜流,致敬编码,致敬未来的自己!
 * @function 函数的功能是:工厂设计中的父类
 *
 */
public abstract class Computer {
    public abstract String getRAM();
    public abstract String getHDD();
    public abstract String getCPU();

    @Override
    public String toString() {
        return  "RAM=【"+this.getRAM()+
                "】HDD=【"+this.getHDD()+
                "】CPU=【"+this.getCPU()+
                "】";
    }
}

  

package com.swust.modle.factory;
/**
 *
 * @author 雪瞳
 * @Slogan 静水潜流,致敬编码,致敬未来的自己!
 * @function 函数的功能是:工厂设计模式中的子类
 *
 */
public class Server extends Computer{
    private String ram;
    private String cpu;
    private String hdd;

    public Server(String ram, String cpu, String hdd) {
        this.ram = ram;
        this.cpu = cpu;
        this.hdd = hdd;
    }

    @Override
    public String getRAM() {
        return this.ram;
    }

    @Override
    public String getHDD() {
        return this.hdd;
    }

    @Override
    public String getCPU() {
        return this.cpu;
    }
}

  

package com.swust.modle.factory;
/**
 *
 * @author 雪瞳
 * @Slogan 静水潜流,致敬编码,致敬未来的自己!
 * @function 函数的功能是:工厂设计模式中的子类
 *
 */
public class PC extends Computer{
    private String ram;
    private String cpu;
    private String hdd;

    public PC(String ram, String cpu, String hdd) {
        this.ram = ram;
        this.cpu = cpu;
        this.hdd = hdd;
    }

    @Override
    public String getRAM() {
        return this.ram;
    }

    @Override
    public String getHDD() {
        return this.hdd;
    }

    @Override
    public String getCPU() {
        return this.cpu;
    }
}

  

package com.swust.modle.factory;

/**
 *
 * @author 雪瞳
 * @Slogan 静水潜流,致敬编码,致敬未来的自己!
 * @function 函数的功能是:模拟工厂设计模式中的工厂类
 */
public class ComputerFactory {

    public static Computer getComputer(String type,String ram,String hdd,String cpu){
        Computer computer;
        if (type.equals("PC")){
             computer  = new PC(ram, cpu, hdd);
        }else if (type.equals("Server")){
             computer = new Server(ram, cpu, hdd);
        }else {
             computer = null;
        }
        return computer;
    }
}

  

package com.swust.modle.factory;

/**
 *
 * @author 雪瞳
 * @Slogan 静水潜流,致敬编码,致敬未来的自己!
 * @function 函数的功能是: 测试简单工厂设计模式
 *
 */
public class TestFactory {
    public static void main(String[] args) {
        String ram = "4g";
        String hdd = "500g";
        String cpu = "6";
        String type = "PC";
        Computer pc = ComputerFactory.getComputer(type, ram, hdd, cpu);
///     调用toString方法
        System.out.println(pc);
    }
}

  

// 运行结果

 

 

猜你喜欢

转载自www.cnblogs.com/walxt/p/12731129.html
今日推荐