引言:抽象工厂只是工厂模式的进一步应用,相信下面的手机生产商例子,可以让大家对比上一篇文章工厂模式,有一个很快速很印象深刻的理解。
一、场景
苹果和三星、小米等,基本是技术宅们的最爱,那么苹果和三星,他们虽然都是手机厂商(MobileFactory
),但是他们所生产的手机的零件都不一样,各有特点。OS
:苹果的IOS,三星的Android;Screen
:苹果的RetinaScreen,三星的OLED屏幕。
于是,就有了如下的设计。
二、设计
贴一张项目结构图,就能清晰明白,抽象工厂模式的基本用法了:
三、简单代码实现
- 抽象工厂类:
public abstract class MobileFactory { protected abstract Os makeOs(); protected abstract Screen makeScreen(); }
- Os接口 与 实现类:
public interface Os { int whichBit(); String msg(); String base(); }
public class Android implements Os { @Override public int whichBit() { return 64; } @Override public String msg() { return "Android欢迎你"; } @Override public String base() { return "Linux"; } }
- Screen抽象类与子类:
public abstract class Screen { protected int width; protected int height; protected abstract void show(); protected abstract int colorCount(); protected int[] deminsion(){ return new int[]{this.width , this.height}; } }
public class LGSoftScreen extends Screen { public LGSoftScreen(){ this.width = 1920; this.height =1080; } public LGSoftScreen(int width, int height){ this.width =width; this.height =height; } @Override public void show() { System.out.println("我是LG柔性屏"); } @Override public int colorCount() { return 32; } }
public class RetinaScreen extends Screen { public RetinaScreen(){ this.width = 2560; this.height = 1600; } @Override protected void show() { System.out.println("Retina LCD 屏"); } @Override protected int colorCount() { return 32; } }
- 好,轮到我们的LG大厂出来啦~
public class LGFactory extends MobileFactory { @Override protected Os makeOs() { return new Android(); } @Override protected Screen makeScreen() { return new LGSoftScreen(800,600); } }
- 我们的苹果大厂~
public class AppleFactory extends MobileFactory { @Override protected Os makeOs() { return new IOS(); } @Override protected Screen makeScreen() { return new RetinaScreen(); } }
谢谢阅读~感谢