抽象工厂设计模式

不打扰是莪最后的温柔 提交于 2019-11-30 07:54:27

抽象工厂设计模式最大特点就是解耦。

//业务需求:生产不同内存条搭配Win7系统的电脑 

//定义抽象工厂
public interface AbstastFactory  {
  public Ram createRam();
  public WinSystem createSys();
}
//具体工厂实现 低端电脑配置
public class LowComputer implements AbstastFactory {
    @Override
    public Ram createRam() { return new Ram512(); }
    @Override
    public WinSystem createSys() { return new SystemWin7(); }
}
//具体工厂实现 高端电脑配置
public class NiceComputer implements AbstastFactory {
    @Override
    public Ram createRam() { return new Ram1G(); }
    @Override
    public WinSystem createSys() { return new SystemWin7(); }
}

//内存条接口
public interface Ram {}
//512内存条实现类
public class Ram1G implements Ram {
    public Ram1G() {
        System.out.println("1G内存");
    }
}

//1G内存条实现类
public class Ram512  implements Ram {
     public  Ram512(){
         System.out.println("512内存");
     }
}
//系统接口
public interface WinSystem {}
//win7系统实现类
public class SystemWin7 implements WinSystem {
    public SystemWin7() {
        System.out.println("win7");
    }
}
//客户类拿到具体产品
public static void main(String[] args) {
        LowComputer lowComputer = new LowComputer();
        lowComputer.createRam();
        lowComputer.createSys();
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!