抽象工厂模式

定义

抽象工厂模式(Abstract Factory),提供一个创建一系列相关或互相依赖对象的接口,而无需指定它们具体的类。

1.抽象产品接口:定义产品的接口,公共的暴露方法。便于实际的产品类实现。

2.具体的产品类:包含实际产品的类的逻辑处理:

3.抽象工厂接口:定义产生系列对象的接口

4.具体的工厂实现:实现抽象的接口工厂,返回具体的产品类的实现。

产品Button 接口

public interface Button {
    
    public void processEvent();
    

产品Text 接口

public interface Text {
    
    public void getWholeText();
    
}

产品Button 接口的实现类LinuxButton

public class LinuxButton implements Button {
 
    @Override
    public void processEvent() {
        System.out.println("Inside LinuxButton::processEvent() method.");
    }
 
}

产品Button 接口的实现类 WindowsButton


public class WindowsButton implements Button {
 
    @Override
    public void processEvent() {
        System.out.println("Inside WindowsButton::processEvent() method.");
    }
 

产品Text 接口的实现类 LinuxText


public class LinuxText implements Text {
 
    @Override
    public void getWholeText() {
        System.out.println("Inside LinuxText::getWholeText() method.");
    }
 
}

产品Text 接口的实现类 WindowsText

public class WindowsText implements Text {
 
    @Override
    public void getWholeText() {
        System.out.println("Inside WindowsText::getWholeText() method.");
    }
 
}

定义抽象工厂

public interface AbstractFactory {
    
    public Button createButton();
    
    public Text createText();
 
}

Linux下的工厂


public class LinuxFactory implements AbstractFactory {
 
    @Override
    public Button createButton() {
        return new LinuxButton();
    }
 
    @Override
    public Text createText() {
        return new LinuxText();
    }
 
}

Windows下的工厂

public class WindowsFactory implements AbstractFactory {
 
    @Override
    public Button createButton() {
        return new WindowsButton();
    }
 
    @Override
    public Text createText() {
        return new WindowsText();
    }
 
}

调用


public class AbstractFactoryDemo {
    
    public static void main(String[] args) {
        AbstractFactory linuxFactory = new LinuxFactory();
        linuxFactory.createButton().processEvent();
        linuxFactory.createText().getWholeText();
        AbstractFactory windowsFactory = new WindowsFactory();
        windowsFactory.createButton().processEvent();
        windowsFactory.createText().getWholeText();
    }
 
}

你可能感兴趣的:(抽象工厂模式)