005 抽象工厂模式

一 .概述

抽象工厂模式的核心就是创建一个产品族.


例子:

现在有一个需要组装一个电脑,其中需要cpu和内存.其中inter的cpu和内存必须一起使用,amd的内存和cpu需要一起使用.

public interface CPU {
    void run();
}
inter的实现
public
class InterCPU implements CPU{ @Override public void run() { System.out.println("inter cpu run "); } }
public class AMDCPU implements CPU{

    @Override
    public void run() {
        System.out.println("AMD cpu run ");
    }

}
public interface Memory {
    void run();
}
public class InterMemory implements Memory{

    @Override
    public void run() {
        System.out.println("AMD memory run");
    }

}
public class AMDMemory implements Memory{

    @Override
    public void run() {
        System.out.println("inter memory run");
    }

}

核心:定义工厂接口.

public interface PCFactory {
    CPU createCPU();
    Memory createMemory();
}

现在这个工厂生产的产品一定是兼容的.

public class InterFactory implements PCFactory{

    @Override
    public CPU createCPU() {
        return new AMDCPU();
    }
    @Override
    public Memory createMemory() {
        return new AMDMemory();
    }
}
public class AMDFactory implements PCFactory{

    @Override
    public CPU createCPU() {
        return new InterCPU();
    }
    @Override
    public Memory createMemory() {
        return new InterMemory();
    }
}

现在客户端使用的时候,只需要从一个工厂之中获得产品就能保证产品的兼容.


扩展:我们的DAO的实现.

现在加入有DAO接口了,那么现在由mysql和oracle的实现.

我们只需要定义一个抽象工厂.这个抽象工厂生产出的产品对我们的项目是兼容的.

不会生成一个mysql的dao,一会又生成一个oracle的dao.


抽象工厂的核心:创建一个兼容的产品族.

原文地址:https://www.cnblogs.com/trekxu/p/8597395.html