1.简单工厂模式,只是介绍使用,实际不实用
package com.test.pattern; /** * @author Ash * @date: 2016年8月8日 下午12:54:35 * @func: 简单工厂模式 * @email [email protected] * @Copyright: 2016 Ash. All rights reserved. */ //产品类 abstract class BMW1 { public BMW1() {} } class BMW1320 extends BMW1 { public BMW1320() { System.out.println("制造 --> BMW320"); } } class BMW1523 extends BMW1 { public BMW1523() { System.out.println("制造 --> BMW523"); } } //工厂类 class Factory { public BMW1 createBMW1(int type) { switch (type) { case 1320: return new BMW1320(); case 1523: return new BMW1523(); default: return null; } } } //客户类 public class Customer1 { public static void main(String[] args) { Factory factory = new Factory(); BMW1 bmw1320 = factory.createBMW1(1320); } }
2.工厂方法模式
package com.test.pattern; /** * @author Ash * @date: 2016年8月8日 下午1:07:40 * @func: 工厂方法模式 * @email [email protected] * @Copyright: 2016 Ash. All rights reserved. */ //产品类 abstract class BMW2 { public BMW2() {} } class BMW2320 extends BMW2 { public BMW2320() { System.out.println("制造 --> BMW320"); } } class BMW2523 extends BMW2 { public BMW2523() { System.out.println("制造 --> BMW2523"); } } //工厂类 interface FactoryBMW2 { BMW2 creaBMW2(); } class FactoryBMW2320 implements FactoryBMW2 { @Override public BMW2 creaBMW2() { return new BMW2320(); } } class FactoryBMW2523 implements FactoryBMW2 { @Override public BMW2 creaBMW2() { return new BMW2523(); } } //客户类 public class Custormer2 { public static void main(String[] args) { FactoryBMW2 factory = new FactoryBMW2320(); factory.creaBMW2(); } }
3.抽象工厂模式
package com.test.pattern; /** * @author Ash * @date: 2016年8月8日 下午1:25:07 * @func: 抽象工厂模式 * @email [email protected] * @Copyright: 2016 Ash. All rights reserved. */ //发动机 interface Engine {} class EngineA implements Engine { public EngineA() { System.out.println("制造 EngineA"); } } class EngineB implements Engine { public EngineB() { System.out.println("制造EngineB"); } } //空调 interface Airconditioner {} class AirconditionerA implements Airconditioner{ public AirconditionerA() { System.out.println("制造AirconditionerA"); } } class AirconditionerB implements Airconditioner{ public AirconditionerB() { System.out.println("制造AirconditionerB"); } } //工厂类 interface AbstractFactory { public Engine createEngine(); public Airconditioner createAirconditioner(); } class FactoryBMW3320 implements AbstractFactory{ @Override public Engine createEngine() { return new EngineA(); } @Override public Airconditioner createAirconditioner() { return new AirconditionerA(); } } class FactoryBMW3523 implements AbstractFactory { @Override public Engine createEngine() { return new EngineB(); } @Override public Airconditioner createAirconditioner() { return new AirconditionerB(); } } public class Customer3 { public static void main(String[] args) { AbstractFactory factory = new FactoryBMW3320(); factory.createAirconditioner(); factory.createEngine(); } }
抽象工厂模式是工厂方法模式的升级版,蛋实际上我觉得没有多大区别,只不过前者的工厂类中有多个生产不同产品的方法而已
时间: 2024-11-05 02:09:52