Java抽象工厂模式

Posted softwarecrash

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java抽象工厂模式相关的知识,希望对你有一定的参考价值。

技术分享图片

EFactory:

public abstract class EFactory {
    abstract public Television produceTelevision();
    abstract public AirConditioner produceAirConditioner();
}

Television:

public interface Television {
    void play();
}

AirConditioner:

public interface AirConditioner {
    void changeTemperature();
}

HaierFactory:

public class HaierFactory extends EFactory{

    @Override
    public Television produceTelevision() {
        return new HaierTelevision();
    }

    @Override
    public AirConditioner produceAirConditioner() {
        return new HaierAirConditioner();
    }
    
}

TCLFactory:

public class TCLFactory extends EFactory{
    @Override
    public Television produceTelevision() {
        return new TCLTelevision();
    }

    @Override
    public AirConditioner produceAirConditioner() {
        return new TCLAirConditioner();
    }
}

HaierTelevision:

public class HaierTelevision implements Television{

    @Override
    public void play() {
        System.out.println("This is HaierTelevision!");
    }
    
}

TCLTelevision:

public class TCLTelevision implements Television{

    @Override
    public void play() {
        System.out.println("This is TCLTelevison!");
    }
    
}

HaierAirConditioner:

public class HaierAirConditioner implements AirConditioner{

    @Override
    public void changeTemperature() {
        System.out.println("This is HaierAirConditioner!");
    }
    
}

TCLAirConditioner:

public class TCLAirConditioner implements AirConditioner{

    @Override
    public void changeTemperature() {
        System.out.println("This is TCLAirConditioner!");
    }
    
}

Factory(调用):

public class Factory {

    public static void main(String[] args) {
        HaierFactory hf = new HaierFactory();
        TCLFactory tclf = new TCLFactory();
        
        AirConditioner hac = hf.produceAirConditioner();
        AirConditioner tclc = tclf.produceAirConditioner();
        
        Television hat = hf.produceTelevision();
        Television tclt = tclf.produceTelevision();
        
        hac.changeTemperature();
        tclc.changeTemperature();
        
        hat.play();
        tclt.play();
    }
    
}

Result:

This is HaierAirConditioner!
This is TCLAirConditioner!
This is HaierTelevision!
This is TCLTelevison!

 




以上是关于Java抽象工厂模式的主要内容,如果未能解决你的问题,请参考以下文章

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

Java设计模式图文代码案例详解Java五大创建者模式 建造者原型(抽象)工厂单例模式

抽象工厂模式(JAVA反射)

大话设计模式-抽象工厂模式(大鸟和小菜Java版)

java抽象工厂的使用意图是啥?

JAVA设计模式——抽象工厂模式案例实现