工厂方法模式(Factory Method)

工厂模式属于创建型模式,如果需要大量的创建实现同一个接口或者类的对象时,可以使用。

简单看下图例:


/**
 * Created by Administrator on 2016/11/18.
 */
public interface Worker {
    public void work();
}

/**
 * Created by Administrator on 2016/11/18.
 */
public class Doctor implements Worker {
    @Override
    public void work() {
        System.out.println("医生开始上班了");
    }
}
/**
 * Created by Administrator on 2016/11/18.
 */
public class Student implements Worker {
    @Override
    public void work() {
        System.out.println("学生开始上课了");
    }
}
/**
 * Created by Administrator on 2016/11/18.
 */
public class Teacher implements Worker {
    @Override
    public void work() {
        System.out.println("教师开始教学了");
    }
}
public class Headmaster extends Teacher{
    public void work(){
        System.out.print("校长开始上班了");
    }
}
/**
 * Created by Administrator on 2016/11/18.
 */
public class WorkFactory {
    public void work(Worker worker){
        worker.work();
    }
    /*
     *多个工厂方法,创建不同的工厂类,外部调用
     */
    public Worker StudentWork(){
        return new Student();
    }
    public Worker TeacherWork(){
        return new Teacher();
    }
    public Worker DoctorWork(){
        return  new Doctor();
    }
    public Worker HeadmasterWork(){
        return new Headmaster();
    }
    /*
     *创建静态工厂类,外部调用
     */
    public static Worker StudentWork1(){
        return new Student();
    }
    public static Worker TeacherWork1(){
        return new Teacher();
    }
    public static Worker DoctorWork1(){
        return new Doctor();
    }
    public static Worker HeadmasterWork1(){
        return new Headmaster();
    }
}
/**
 * Created by Administrator on 2016/11/18.
 */
public class Test {
    public static void main(String[] args){
        WorkFactory factory = new WorkFactory();
        factory.work(new Doctor());
        factory.work(new Teacher());
        factory.work(new Student());
        factory.work(new Headmaster());

        factory.DoctorWork().work();
        factory.TeacherWork().work();
        factory.StudentWork().work();
        factory.HeadmasterWork().work();

        WorkFactory.DoctorWork1().work();
        WorkFactory.TeacherWork1().work();
        WorkFactory.StudentWork1().work();
        WorkFactory.HeadmasterWork1().work();
    }
}





发布了198 篇原创文章 · 获赞 21 · 访问量 22万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览