设计模式之工厂方法模式实例(Java)

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

package AirCondition;

public class test {
	public static void main(String[] args) {
		AirFactory airfactory=new HaierAirFactory();
		Air air=airfactory.ProduceAir();
		airfactory=new MideaAirFactory();
		air=airfactory.ProduceAir();
	}
}
package AirCondition;

public interface Air {
	public void work();
}
package AirCondition;

public class HaierAir implements Air{
	public void work() {
		System.out.println("海尔工厂正在生产海尔空调!");
	}

}
package AirCondition;

public class MideaAir implements Air{
	public void work() {
		System.out.println("美的工厂正在生产美的空调!");
		
	}

}
package AirCondition;

public interface AirFactory {
	Air ProduceAir();

}

package AirCondition;

public class HaierAirFactory implements AirFactory{
	public HaierAir ProduceAir() {
		System.out.println("生产了海尔空调!");
		return new HaierAir();
	}

}
package AirCondition;

public class MideaAirFactory implements AirFactory{
	public MideaAir ProduceAir() {
		System.out.println("生产了美的空调!");
		return new MideaAir();
	}

}

你可能感兴趣的:(设计模式之工厂方法模式实例(Java))