建造者模式

建造者模式:

                  将一个复杂的对象的创建过程和显示分离出来,使得同样的创建过程可以有不同的表示;

组成:

        一个复杂基类;

        一个抽象类(抽象出设置复杂类的属性和获得对象)

        一个实现细节类,需要继承上面的抽象类;

        建造者类,通过实现细节类,获取所需个个性复杂类;

代码如下:

public class Student { //复杂基类

    private String name ;
    private int age;
    private String grade;

    public String showInfo(){
        return  "name:"+name+" age:"+ age+ "  grade:" + grade;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }
}
//抽象类

abstract class School {

    public abstract void setInfo(String name,int age,String grade);

    public abstract Student getStudent();
}

//细节实现类

public class Class extends School {

    private Student student = new Student();

    @Override
    public void setInfo(String name, int age, String grade) {
        student.setName(name);
        student.setAge(age);
        student.setGrade(grade);
    }

    @Override
    public Student getStudent() {
        return student;
    }


}

//建造者类

public class Teacher {

    private Class clazz =  new Class();

    public Student student_A(){
        clazz.setInfo("xiaoming",10,"三年级");
        return  clazz.getStudent();
    }

    public Student student_B(){
        clazz.setInfo("xiaohua",13,"grade");
        return clazz.getStudent();
    }
}

//测试类

public class Test {

    public static void main(String[] args){
        Teacher teacher = new Teacher();
        Student student1 =  teacher.student_A();
        String info1 = student1.showInfo();

        Student student2 = teacher.student_B();
        String info2 = student2.showInfo();

        System.out.println(info1);
        System.out.println(info2);
    }
}


你可能感兴趣的:(Java基础知识,23中设计模式)