单例模式
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();