Abstract Factory模式的意图:
提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
我的理解:
抽象工厂定义了可以创建产品的种类,然后针对不同的需要使用不同的子工厂创建相应的产品!
实例:一个电脑硬件厂商要生产两种不同的硬盘和内存。
AbstractFactory.java
/**
* filename:Test.java
* createtime:2011-4-8上午12:22:59
* author:wustrive_2008
* E-mail:wustrive_2008@126.com
*/
package com.gufengxiachen.designpatterns.abstractfactory;
public abstract class AbstractFactory {
public abstract AbstractHardDisk getHardDisk();
public abstract AbstractMemory getMemory();
}
AbstractHardDisk.java:
/**
* filename:Test.java
* createtime:2011-4-8上午12:22:59
* author:wustrive_2008
* E-mail:wustrive_2008@126.com
*/
package com.gufengxiachen.designpatterns.abstractfactory;
public abstract class AbstractHardDisk {
public abstract void textHardDisk();
}
class HardDiskA extends AbstractHardDisk{
@Override
public void textHardDisk() {
System.out.println("硬盘A生产成功");
}
}
class HardDiskB extends AbstractHardDisk{
@Override
public void textHardDisk() {
System.out.println("硬盘B生产成功");
}
}
AbstractMemeory.java:
/**
* filename:Test.java
* createtime:2011-4-8上午12:22:59
* author:wustrive_2008
* E-mail:wustrive_2008@126.com
*/
package com.gufengxiachen.designpatterns.abstractfactory;
public abstract class AbstractMemory {
public abstract void textMemory();
}
class MemoryA extends AbstractMemory{
@Override
public void textMemory() {
System.out.println("内存A生产成功");
}
}
class MemoryB extends AbstractMemory{
@Override
public void textMemory() {
System.out.println("内存B生产成功");
}
}
AFactory.java:
/**
* filename:Test.java
* createtime:2011-4-8上午12:22:59
* author:wustrive_2008
* E-mail:wustrive_2008@126.com
*/
package com.gufengxiachen.designpatterns.abstractfactory;
public class AFactory extends AbstractFactory{
@Override
public AbstractHardDisk getHardDisk() {
// TODO Auto-generated method stub
return new HardDiskA();
}
@Override
public AbstractMemory getMemory() {
// TODO Auto-generated method stub
return new MemoryA();
}
}
BFactory.java:
/**
* filename:Test.java
* createtime:2011-4-8上午12:22:59
* author:wustrive_2008
* E-mail:wustrive_2008@126.com
*/
package com.gufengxiachen.designpatterns.abstractfactory;
public class BFactory extends AbstractFactory{
@Override
public AbstractHardDisk getHardDisk() {
// TODO Auto-generated method stub
return new HardDiskB();
}
@Override
public AbstractMemory getMemory() {
// TODO Auto-generated method stub
return new MemoryB();
}
}
Client.java:
/**
* filename:Test.java
* createtime:2011-4-8上午12:22:59
* author:wustrive_2008
* E-mail:wustrive_2008@126.com
*/
package com.gufengxiachen.designpatterns.abstractfactory;
public class Client {
public static void main(String[] args) {
AbstractFactory af=new BFactory();
AbstractHardDisk hd= af.getHardDisk();
AbstractMemory ma=af.getMemory();
hd.textHardDisk();
ma.textMemory();
}
}
在以下情况下可以使用 抽象工厂:
一个系统要独立于它的产品的创建、组合和表示时。
一个系统要由多个产品系列中的一个来配置时。
只想显示产品的接口而非实现时
抽象工厂模式的优缺点:
优点:它分离了具体的类,它使得易于交换产品系列
缺点:难以支持新种类的产品