工厂模式--简单工厂
程序员文章站
2024-01-20 16:25:58
...
学习设计模式的几点说明:1)应用场景;2)UML类图;3)代码。
关于工厂模式中简单工厂代码。
package test6.simpleFactory;
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...");
}
}
class CarFactory {
public static final int BENZ_CAR = 1;
public static final int BMW_CAR = 2;
public static Car createCarFactor(int type) {
if(type == CarFactory.BENZ_CAR) {
return new BenzCar();
} else if (type == CarFactory.BMW_CAR) {
return new BMWCar();
}
return null;
}
}
public class Application {
@Test
public void test() {
Car car = CarFactory.createCarFactor(CarFactory.BENZ_CAR);
car.printName();
car = CarFactory.createCarFactor(CarFactory.BMW_CAR);
car.printName();
}
}
上一篇: 基于xml文件的AOP配置
下一篇: Test_集合_HashSet