设计模式--2创建型设计模式--简单工厂

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/river472242652/article/details/79494800
package cn.riversky.create.simplefactory;

/**
 * 简单工厂模式:定义一个工厂类,根据传入的参数构造生成不同的实例。一般通过静态方法的方式进行构建。
 * 因此也称为静态工厂方法模式
 * 这里设计学生抽象类,和两个实现类(班长类,助教类),和工厂类(简单工厂)
 * @author riversky E-mail:[email protected]
 * @version 创建时间 : 2018/3/9.
 */
public class Client {
    public static void main(String[] args) {
        Student student=StudentFactory.getStudent("zhujiao");
        student.work();
         student=StudentFactory.getStudent("banzhang");
        student.work();
    }
}
package cn.riversky.create.simplefactory;

/**学生类
 * @author riversky E-mail:[email protected]
 * @version 创建时间 : 2018/3/9.
 */
public abstract class Student {
    public void study(){
        System.out.println("学习");
    }
    public abstract  void work();
}
package cn.riversky.create.simplefactory;

/**助教类
 * @author riversky E-mail:[email protected]
 * @version 创建时间 : 2018/3/9.
 */
public class HelpStudy extends Student {
    public void work() {
        System.out.println("开机,备课");
        study();
    }
}
package cn.riversky.create.simplefactory;

/**班长类
 * @author riversky E-mail:[email protected]
 * @version 创建时间 : 2018/3/9.
 */
public class Banzhang extends Student {
    public void work() {
        System.out.println("点名");
        study();
    }
}
package cn.riversky.create.simplefactory;

/**简单工厂类
 * @author riversky E-mail:[email protected]
 * @version 创建时间 : 2018/3/9.
 */
public class StudentFactory {
    public static Student getStudent(String arg){
        Student student=null;
        if(arg!=null&&!arg.equals("")){
            if(arg.equals("banzhang")){
                student=new Banzhang();
            }else  {
                student=new HelpStudy();
            }
        }else {
            student=new HelpStudy();
        }
        return student;
    }
}

猜你喜欢

转载自blog.csdn.net/river472242652/article/details/79494800