public interface Car {
void run();
}
public class Audi implements Car {
@Override
public void run() {
System.out.println("奥迪再跑!");
}
}
public class Byd implements Car {
@Override
public void run() {
System.out.println("比亚迪再跑!");
}
}
public class CarFactory {
public static Car createCar(String type){
if("奥迪".equals(type)){
return new Audi();
}else if("比亚迪".equals(type)){
return new Byd();
}else{
return null;
}
}
}
public class CarFactory2 {
public static Car createAudi(){
return new Audi();
}
public static Car createByd(){
return new Byd();
}
}
//这种方式如果需要添加新的车型,需要改工厂类的代码,不符合OCP
public interface Car {
void run();
}
public interface CarFactory {
Car createCar();
}
public class Audi implements Car {
@Override
public void run() {
System.out.println("奥迪再跑!");
}
}
public class Byd implements Car {
@Override
public void run() {
System.out.println("比亚迪再跑!");
}
}
public class AudiFactory implements CarFactory {
@Override
public Car createCar() {
return new Audi();
}
}
public class BenzFactory implements CarFactory {
@Override
public Car createCar() {
return new Benz();
}
}
//这种方式是如果需要添加新的车,不需要改原有的工厂类的代码,只需要继续创建新的对象
//更符合OCP,但这种方式的结构复杂度、代码复杂度、以及编程难度更高,常用简单工厂模式
public interface Tyre {
void revolve();
}
class BcTyre implements Tyre {
@Override
public void revolve() {
System.out.println("奔驰轮胎");
}
}
class BydTyre implements Tyre {
@Override
public void revolve() {
System.out.println("比亚迪轮胎");
}
}
-----------------------------------------------
public interface Seat {
void massage();
}
class BcSeat implements Seat {
@Override
public void massage() {
System.out.println("奔驰座椅");
}
}
class BydSeat implements Seat {
@Override
public void massage() {
System.out.println("比亚迪座椅");
}
}
-----------------------------------------------------------------
public interface Engine {
void run();
}
class BcEngine implements Engine{
@Override
public void run() {
System.out.println("奔驰的引擎");
}
}
class BydEngine implements Engine{
@Override
public void run() {
System.out.println("比亚迪的引擎");
}
}
public class BydCarFactory implements CarFactory {
//比亚迪车的工厂
@Override
public Engine createEngine() {
return new BydEngine();
}
@Override
public Seat createSeat() {
return new BydSeat();
}
@Override
public Tyre createTyre() {
return new BydTyre();
}
}
public class BcCarFactory implements CarFactory {
//奔驰车的工厂
@Override
public Engine createEngine() {
return new BcEngine();
}
@Override
public Seat createSeat() {
return new BcSeat();
}
@Override
public Tyre createTyre() {
return new BcTyre();
}
}
public interface CarFactory {
Engine createEngine();
Seat createSeat();
Tyre createTyre();
}