设计模式--工厂模式案例

原文链接

/**
 * 抽象用户接口
 * @author easypanda
 * @date 2018-06-28
 */
public interface User {

}
/**
 * 学生类
 * @author easypanda
 * @date 2018-06-28
 */
public class Student implements User{
    private String id;
    private String name;
    private String sex;
    private String age;
    //省略get set
}
/**
 * 教师类
 * @author easypanda
 * @date 2018-06-28
 */
public class Teacher {
    private String id;
    private String name;
    private String sex;
    private String age;
    private String course;//教学科目
    //省略get set
}



/**
 * 用户类型枚举
 * @author easypanda
 * @date 2018-06-28
 */
public enum UserType {
    STUDENT,TEACHER;
}
/**
 * 用户工厂,可以产生各类用户
 * @author easypanda
 * @date 2018-06-28
 */
public class UserFactory {
    public static User createUser(UserType userType){
        if(userType==UserType.TEACHER)
            return new Teacher();
        else if(userType==UserType.TEACHER)
            return new Student();
    }
}

User user=UserFactory.createUser(UserType.STUDENT);

你可能感兴趣的:(设计模式--工厂模式案例)