抽象工厂模式:
模式动机
为了更清晰地理解工厂方法模式,需要先引入两个概念:
|
模式定义
抽象工厂模式(Abstract Factory Pattern):提供一个创建一系列相关或相互依赖对象的接口,而无须指定它们具体的类。抽象工厂模式又称为Kit模式,属于对象创建型模式。 |
模式结构
抽象工厂模式包含如下角色:
|
时序图
代码分析
public interface Seat {//椅子 public void massage(); } class LuxurySeat implements Seat{ @Override public void massage() { System.out.println("可以按摩的座椅"); } } class LowerSeat implements Seat{
@Override public void massage() { System.out.println("不能按摩的座椅"); } } public interface Engine { public void run(); public void start(); } class LuxuryEngine implements Engine{ @Override public void run() { System.out.println("跑的快"); } @Override public void start() { System.out.println("启动的快"); } } class LowerEngine implements Engine{ @Override public void run() { System.out.println("跑的慢"); } @Override public void start() { System.out.println("启动的慢"); } } public interface Tyre { public void revlove(); } class LuxuryTyre implements Tyre{ @Override public void revlove() { System.out.println("磨损慢!!"); } } class LowerTyre implements Tyre{ @Override public void revlove() { System.out.println("磨损快!!"); } } /** * 抽象工厂模式,产品族的概念; * 某个对象,是由若干个产品组成,而每个产品都有对应的产品族; * (1)需要将每个产品定义为接口,然后不同的产品进行实现; * (2)定义对象的接口,对象的实现类是各个产品族的组合; * @author jack */ public interface CarFactory { Engine createEngine(); Seat createSeat(); Tyre creatTyre(); } class LuxuryCarFactory implements CarFactory{ @Override public Engine createEngine() { return new LuxuryEngine(); } @Override public Seat createSeat() { return new LuxurySeat(); } @Override public Tyre creatTyre() { return new LuxuryTyre(); } } class LowerCarFactory implements CarFactory{ @Override public Engine createEngine() { return new LowerEngine(); } @Override public Seat createSeat() { return new LowerSeat(); } @Override public Tyre creatTyre() { return new LowerTyre(); } } public class Client1 { public static void main(String[] args) { LuxuryCarFactory luxuryCarFactory = new LuxuryCarFactory(); luxuryCarFactory.createEngine().run(); luxuryCarFactory.createSeat().massage(); luxuryCarFactory.creatTyre().revlove(); } }
|
如有疑问,请发邮件:1176306419@qq.com
github:https://github.com/wangrui0/