工厂模式
一般推荐使用简单工厂模式--构建汽车接口、独特车型实现接口、工厂根据用户想要的车型常见新车返回给用户
1 public interface Car { 2 void run(); 3 }
public class Audi implements Car{ @Override public void run() { System.out.println("Audi is running!"); } }
public class Byd implements Car{ @Override public void run() { System.out.println("Byd is running!"); } }
1 public class SimpleFactoryDemo { 2 public static Car createCar(String type){ 3 Car c = null; 4 if(type.equals("Audi")){ 5 c = new Audi(); 6 return c; 7 }else if(type.equals("Byd")){ 8 c = new Byd(); 9 return c; 10 } 11 return c; 12 } 13 }
1 //调用者只需调用工厂,让工厂返回对象。不需要调用者自己创建new对象。 2 public class Client { 3 public static void main(String[] args) { 4 Car c1 = SimpleFactoryDemo.createCar("Audi"); 5 Car c2 = SimpleFactoryDemo.createCar("Byd"); 6 c1.run(); 7 c2.run(); 8 } 9 } 10 11 12 输出:Audi is running! 13 Byd is running!
抽象工厂模式适用于产品族系列。相当于生产要都是一个系列的。每个工厂生产所需的组件不同但是一系列的。
1 //发动机分为好的与一般的两个系列 2 public interface Engine { 3 void mess(); 4 } 5 class AdvancedEngine implements Engine{ 6 @Override 7 public void mess() { 8 System.out.println("faster"); 9 } 10 } 11 class LowerEngine implements Engine{ 12 @Override 13 public void mess() { 14 System.out.println("normal"); 15 } 16 }
//镜子也分为好于一般的 public interface Mirror { void mess(); } class AdvancedMirror implements Mirror{ @Override public void mess() { System.out.println("better"); } } class LowerMirror implements Mirror{ @Override public void mess() { System.out.println("good"); } }
1 //座椅也分为好的与一般的 2 public interface Seat { 3 void mess(); 4 } 5 class AdvancedSeat implements Seat{ 6 @Override 7 public void mess() { 8 System.out.println("thick"); 9 } 10 } 11 class LowerSeat implements Seat{ 12 @Override 13 public void mess() { 14 System.out.println("thin"); 15 } 16 }
1 //汽车工厂类的行为 2 public interface CarFactory { 3 Engine createEngine(); 4 Seat createSeat(); 5 Mirror createMirror(); 6 }
1 //好的工厂创建它的好产品系列 2 public class AdvancedFactory implements CarFactory{ 3 @Override 4 public Engine createEngine() { 5 return new AdvancedEngine(); 6 } 7 @Override 8 public Seat createSeat() { 9 return new AdvancedSeat(); 10 } 11 @Override 12 public Mirror createMirror() { 13 return new AdvancedMirror(); 14 } 15 }
1 //一般工厂创建它的一般产品系列 2 public class LowerFactory implements CarFactory{ 3 @Override 4 public Engine createEngine() { 5 return new LowerEngine(); 6 } 7 @Override 8 public Seat createSeat() { 9 return new LowerSeat(); 10 } 11 @Override 12 public Mirror createMirror() { 13 return new LowerMirror(); 14 } 15 }
1 //抽象工厂创建产品 2 public class AbstractFactoryDemo { 3 public static void main(String[] args) { 4 CarFactory c = new AdvancedFactory(); 5 Engine e = c.createEngine(); 6 Mirror m = c.createMirror(); 7 Seat s = c.createSeat(); 8 e.mess(); 9 m.mess(); 10 s.mess(); 11 } 12 } 13 14 输出:faster 15 better 16 thick