工厂模式--抽象工厂

学习设计模式的几点说明:1)应用场景;2)UML类图;3)代码。

 

工厂模式中抽象工厂代码。

 

 

package test6.abstractFactory;

import org.junit.Test;

abstract class Car {
	public abstract void printName();
}

class BenzCar extends Car {

	@Override
	public void printName() {
		System.out.println("Benz Car...");
		
	}
	
}

class BMWCar extends Car {

	@Override
	public void printName() {
		System.out.println("BMW Car...");
		
	}
	
}


abstract class CarFactory {
	public abstract Car createCar();
	
	public static CarFactory newFactoryInstance(String carFactoryType) throws Exception {
		Class<?> c = Class.forName(carFactoryType);
		return (CarFactory)c.newInstance();
	}
}

class BenzCarFactory extends CarFactory {

	@Override
	public Car createCar() {
		return new BenzCar();
	}
	
}

class BMWCarFactory extends CarFactory {

	@Override
	public Car createCar() {
		return new BMWCar();
	}
	
}

public class Application {

	@Test
	public void test() throws Exception {
		CarFactory factory = CarFactory.newFactoryInstance("test6.abstractFactory.BenzCarFactory");
		Car car = factory.createCar();
		car.printName();
		
		factory = CarFactory.newFactoryInstance("test6.abstractFactory.BMWCarFactory");
		car = factory.createCar();
		car.printName();
	}
}
 

你可能感兴趣的:(设计模式,C++,c,JUnit,UML)