一起学Java设计模式--工厂方法模式(不在23种设计模式之内)

(2) 工厂方法模式

海尔工厂(Haier)生产海尔空调(HaierAirCondition),美的工厂(Midea)生产美的空调(MideaAirCondition) 。使用工厂方法模式描述该场景,绘制类图并编程实现。

一起学Java设计模式--工厂方法模式(不在23种设计模式之内)_第1张图片

public interface AirCondition{

	void work();

}
public interface AirConditionFactory{

	AirCondition produceAirCondition();

}
public class HaierAirCondition implements AirCondition{
	public void work(){

		System.out.println("HaierAirCondition is working! -_-!!!");

	}
}


public class MideaAirCondition implements AirCondition{
	public void work(){

		System.out.println("MideaAirCondition is working -_-~~~");

	}
}
public class HaierAirConditionFactory implements AirConditionFactory{
	public HaierAirCondition produceAirCondition(){

		System.out.println("HaierAirCondition produced! *^_^*");

		return new HaierAirCondition();
	}
}

public class MideaAirConditionFactory implements AirConditionFactory{
	public MideaAirCondition produceAirCondition(){
	
		System.out.println("MideaAirCondition produced! *^_^*");
		
		return new MideaAirCondition();
	}
}
public class AirConditionClient{
	public static void main(String[] args){
		AirCondition haierCondition, mideaCondition;
		
		AirConditionFactory haierConditionFactory = new HaierAirConditionFactory();
		AirConditionFactory mideaConditionFactory = new MideaAirConditionFactory();
		
		haierCondition = haierConditionFactory.produceAirCondition();
		mideaCondition = mideaConditionFactory.produceAirCondition();
		
		haierCondition.work();
		System.out.println();
		mideaCondition.work();
		
	}
}

运行结果:

一起学Java设计模式--工厂方法模式(不在23种设计模式之内)_第2张图片


你可能感兴趣的:(Java设计模式)