简单工厂模式:也可以叫做是静态工厂模式,属于类创建型模式,根据不同的参数,返回不同的类实现、 *三个角色: * 抽象产品角色:一般用接口 或 抽象类实现

53 阅读1分钟

```
import org.junit.Test;

/**
* @author samxie
* @version 1.0
* @date 2022/5/26 10:39
**/
public class TestSimpleFactory {
/**简单工厂模式:也可以叫做是静态工厂模式,属于类创建型模式,根据不同的参数,返回不同的类实现、
* 三个角色:
* 抽象产品角色:一般用接口 或 抽象类实现
* 具体的产品角色:具体的类实现
* 工厂角色:实例的产生,根据不同参数,返回不同的类实现
*/
@Test
public void test() {
//上班方式1
Car car = SimpleFactory.getCar(1);
System.out.println("上班方式");
car.goToWork();

        //上班方式2
Car car1 = SimpleFactory.getCar(2);
System.out.println("上班方式");
car1.goToWork();

        //比较一下
Car bike = new Bike();
System.out.println("上班方式");
bike.goToWork();
}
}

//车?什么车?自行车、公交车
interface Car {
//上班的方法,这个事情是上班
void goToWork();
}

//具体产品角色
class Bike implements Car {

    @Override
public void goToWork() {
System.out.println("骑单车上班");
}
}

//具体产品角色
class Bus implements Car {

    @Override
public void goToWork() {
System.out.println("坐公交上班");
}
}

//工厂角色,实际实例的生产者
class SimpleFactory {

    public static Car getCar(Integer type) {
if (null == type) {
return null;
}
if (1 == type) {
Car bike = new Bike();
return bike;
} else if (2 == type) {
Car bus = new Bus();
return bus;
}
return null;
}
}

```

本文使用 文章同步助手 同步