用于实例化对象的三种设计模式

单例模式

public class Manager {
    private static Manager manager;

    private Manager() {
    }
    
    public static Manager getInstance(){
        if (manager == null){
            synchronized (Manager.class){
                if (manager == null){
                    manager = new Manager();
                }
            }
        }
        return manager;
    }
}

注意

     1、构造方法私有化

     2、双重判空

     3、加锁保证同步

 

工厂模式

public interface Computer {
    void compute();
}


public class Dell implements Computer {
    @Override
    public void compute() {
        System.out.println("dell compute.....");
    }
}


public class Thinkpad implements Computer {
    @Override
    public void compute() {
        System.out.println("thinkpad compute.....");
    }
}


public class ComputerFactory {
    public static Computer createDell(){
        return new Dell();
    }

    public static Computer createThinkpad(){
        return new Thinkpad();
    }
}

 

构造者模式

public class Student {

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}


public class StudentParams {
    //必需参数
    public String name;
    public int age;
    
    //非必需参数
    public String grade = "一班";
    public String sex = "男";
}

public class StudentBuilder {
    private final StudentParams params;

    //必需参数可以写入到构造方法中
    public StudentBuilder(String name, int age) {
        params = new StudentParams();
        params.name = name;
        params.age = age;
    }

    public StudentBuilder grade(String grade){
        params.grade = grade;
        return  this;
    }

    public StudentBuilder sex(String sex){
        params.sex = sex;
        return this;
    }

    public Student build(){
        Student student = new Student();
        student.setAge(params.age);
        student.setName(params.name);
        student.setGrade(params.grade);
        student.setSex(params.sex);
        return student;
    }
}


//调用
Student student = new StudentBuilder("张三",18)
                .grade("二班")
                .sex("女")
                .build();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值