1、工厂设计模式
用来生产类对象,避免用户直接接触派生类
给出一个例子:
接口:Teacher
interface Teacher{ public void teach(); }
class EnglishTeacher implements Teacher{ public void teach(){ System.out.println("上英语课"); } }
class MathTeacher implements Teacher{ public void teach(){ System.out.println("上数学课"); } }
class TeacherFactory{ public static Teacher getTeacher(int flag){ Teacher teacher = null; if(0 == flag){ teacher = new EnglishTeacher(); } else if(1 == flag ){ teacher = new MathTeacher(); } return teacher; } }
class Test{ public static void main(String args []){ int flag = 1; Teacher teacher = TeacherFactory.getTeacher(flag); teacher.teach(); } }
2、装饰者设计模式
主要用于降低继承的复杂度
在上面的基础上修改代码
class GradeOne implements Teacher{ Teacher gradeOneTeacher = null; GradeOne(Teacher teacher){ gradeOneTeacher = teacher; } public void teach(){ System.out.println("我是一年级的老师"); gradeOneTeacher.teach(); } }
class GradeTwo implements Teacher{ Teacher gradeTwoTeacher = null; GradeTwo(Teacher teacher){ gradeTwoTeacher = teacher; } public void teach(){ System.out.println("我是二年级的老师"); gradeTwoTeacher.teach(); } }
class Test{ public static void main(String args []){ //下面的方法是申请一个一年级的数学老师 //装饰者模式 int flag = 1; Teacher teacher = TeacherFactory.getTeacher(flag); GradeOne gradeOneTeacher = new GradeOne(teacher); gradeOneTeacher.teach(); } }