设计模式-03-抽象工厂模式

本文深入解析抽象工厂模式,包括其与工厂模式的区别、特点、角色及应用场景等,并通过实例代码展示了如何实现该模式。

设计模式-03-抽象工厂模式


本文大部分参考自《java与模式》

一、与工厂模式的异同

1.工厂模式是针对一个产品。

2.抽象工厂模式是针对有一定关系的多个不同产品。

二、特点

1.每个产品族都有一个具体工厂,也就是说每个具体工厂都可以生产全部产品,只是他生产的样式不同与其他工厂的。

2.抽象工厂里的声明了可创建的产品族,有多少个产品,在抽象工厂里便有多少个创建方法。

三、角色

1.IFactory:包含产品族的创建方法。

2.IProductA:产品A的抽象父类。

3.IProductB:产品B的抽象父类。

4.ConcreteFactory1:创建1号类型的产品族的具体工厂。

5.ConcreteFactory2:创建2号类型的产品族的具体工厂。

6.ProductA1:具体工厂1创建的ProductA。

7.ProductA2:具体工厂2创建的ProductB。

8.ProductB1

9.ProductB2

四、UML类图


五、Code

1.抽象工厂类

package com.jue.dp;

public interface IFactory {

	IProductA newA();

	IProductB newB();

}

2.抽象产品类A

package com.jue.dp;

public interface IProductA {

	void display();
}

3.抽象产品类B

package com.jue.dp;

public interface IProductB {

	void spell();
}

4.具体工厂类1

package com.jue.dp;

public class ConcreteFactory1 implements IFactory {

	@Override
	public IProductA newA() {
		return new ProductA1();
	}

	@Override
	public IProductB newB() {
		return new ProductB1();
	}

}

5.具体工厂类2

package com.jue.dp;

public class ConcreteFactory2 implements IFactory {

	@Override
	public IProductA newA() {
		return new ProductA2();
	}

	@Override
	public IProductB newB() {
		return new ProductB2();
	}

}

6.具体产品A1

package com.jue.dp;

public class ProductA1 implements IProductA {

	@Override
	public void display() {
		System.out.println("ProductA1->display");
	}

}

7.具体产品B1

package com.jue.dp;

public class ProductB1 implements IProductB {

	@Override
	public void spell() {
		System.out.println("ProductB1->good spell");
	}

}

8.具体产品A2

package com.jue.dp;

public class ProductA2 implements IProductA {

	@Override
	public void display() {
		System.out.println("ProductA2->display");
	}

}

9.具体产品B2

package com.jue.dp;

public class ProductB2 implements IProductB {

	@Override
	public void spell() {
		System.out.println("ProductB2->good spell");		
	}

}

10.测试类

package com.jue.dp;

public class MainClass {

	public static void main(String[] args) {
		IFactory f1 = new ConcreteFactory1();
		IProductA pa = f1.newA();
		IProductB pb = f1.newB();
		pa.display();
		pb.spell();
	}

}

六、使用场景

1.客户端不关心产品的创建细节,只关心消费产品。

2.系统中的需要创建的产品族有多个产品,并且这些产品中有一定的关系。

七、抽象模式的起源

创建分属于不同操作系统的视窗控件。


八、关于开闭原则

1.产品的数目的扩展:不支持开闭原则(因为抽象工厂方法数目本身就是基于产品的数目)

2.产品族的扩展:支持开闭原则。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值