关闭

简单工厂模式

标签: java简单工厂模式
81人阅读 评论(0) 收藏 举报
分类:
  1. Factory

    • 顶层接口
package com.wayne.factory;

import com.wayne.pojo.IMoveable;

public interface IVichelFactory {
    IMoveable create();
}
  • 两个实现类

CarFactory.java

package com.wayne.factory;

import com.wayne.pojo.Car;
import com.wayne.pojo.IMoveable;

public class CarFactory implements IVichelFactory {

    @Override
    public IMoveable create() {
        return new Car();
    }

}

PlaneFactory.java

package com.wayne.factory;

import com.wayne.pojo.IMoveable;
import com.wayne.pojo.Plane;

public class PlaneFactory implements IVichelFactory {

    @Override
    public IMoveable create() {
        return new Plane();
    }

}
  1. pojo

    • 顶层接口
package com.wayne.pojo;

public interface IMoveable {
    void run();
}
  • 两个实现类

Car.java

package com.wayne.pojo;

public class Car implements IMoveable {

    @Override
    public void run() {
        System.out.println("Car来了。。。。。。");
    }

}

Plane.java

package com.wayne.pojo;

public class Plane implements IMoveable {

    @Override
    public void run() {
        System.out.println("Plane飞来了");
    }

}
  1. test
package com.wayne.test;

import com.wayne.factory.IVichelFactory;
import com.wayne.factory.PlaneFactory;
import com.wayne.pojo.IMoveable;

public class MyTest {

    public static void main(String[] args) {
        IVichelFactory factory = new PlaneFactory();
        //IVichelFactory factory = new CarFactory();
        IMoveable m = factory.create();
        m.run();
    }

}

总结:
一个模块对扩展应是开放的,对修改应是关闭的。

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:13848次
    • 积分:350
    • 等级:
    • 排名:千里之外
    • 原创:21篇
    • 转载:1篇
    • 译文:1篇
    • 评论:0条
    文章分类