实例化对象不使用new,用工厂方法实现
将选择实现类,创建对象统一管理和控制。从而将调用者跟实现类解耦
简单工厂模式
工厂方法模式
抽象工厂模式
虽然某种程度上不符合设计原则,但实际使用最多
不修改已知类的前提下,通过增加新的工厂类实现扩展
不可以增加产品,可以增加产品族
实现之车工厂
package com.li.factory.simple;
public interface Car {
void name();
}
WuLing.java
package com.li.factory.simple;
public class WuLing implements Car {
@Override
public void name() {
System.out.println("五菱宏光!");
}
}
Tesla.java
package com.li.factory.simple;
public class Tesla implements Car {
@Override
public void name() {
System.out.println("特斯拉!");
}
}
Dazhong.java
package com.li.factory.simple;
public class Dazhong implements Car {
@Override
public void name() {
System.out.println("大众!");
}
}
CarFactory.java
package com.li.factory.simple;
//简单工厂模式也称静态工厂模式
//增加一个新的产品,如果不修改代码,做不到!
//开闭原则
public class CarFactory {
//方法一
public static Car getCar(String car){
if(car.equals("五菱")){
return new WuLing();
}else if(car.equals("特斯拉")){
return new Tesla();
}else {
return null;
}
}
//方法二
public static Car getWuling(){
return new WuLing();
}
public static Car getTesla(){
return new Tesla();
}
}
测试
Consumer.java
package com.li.factory.simple;
public class Comsumer {
public static void main(String[] args) {
//接口,所有的实现类!工厂
//Car car = new WuLing();
// Car car2 = new Tesla();
//使用工厂创建
Car car = CarFactory.getCar("五菱");
Car car2 = CarFactory.getCar("特斯拉");
car.name();
car2.name();
}
}
package com.li.factory.simple;
public interface Car {
void name();
}
WuLing.java
package com.li.factory.method;
public class WuLing implements Car {
@Override
public void name() {
System.out.println("五菱宏光!");
}
}
Tesla.java
package com.li.factory.method;
public class Tesla implements Car {
@Override
public void name() {
System.out.println("特斯拉!");
}
}
MoBai.java
package com.li.factory.method;
public class MoBai implements Car {
@Override
public void name() {
System.out.println("摩拜单车!");
}
}
CarFactory.java
package com.li.factory.method;
public interface CarFactory {
Car getCar();
}
WuLingFactory.java
package com.li.factory.method;
public class WuLingFactory implements CarFactory {
@Override
public Car getCar() {
return new WuLing();
}
}
TeslaFactory.java
package com.li.factory.method;
public class TeslaFactory implements CarFactory {
@Override
public Car getCar() {
return new Tesla();
}
}
MoBaiFactory.java
package com.li.factory.method;
public class MoBaiFactory implements CarFactory {
@Override
public Car getCar() {
return new MoBai();
}
}
测试
Comsumer.java
package com.li.factory.method;
public class Comsumer {
public static void main(String[] args) {
Car car = new WuLingFactory().getCar();
Car car2 = new TeslaFactory().getCar();
car.name();
car2.name();
Car car3 = new MoBaiFactory().getCar();
car3.name();
}
//结构复杂度:sample
//代码复杂度:sample
//编程复杂度:sample
//管理上的复杂度: sample
//根据设计原则: 工厂方法模式!
//根据实际业务: 简单工厂模式!
}