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!