一、单例模式
- 饱汉模式
public class SinglePattern2 { private SinglePattern2 sp; public SinglePattern2 getInstance() { if (sp == null) { return new SinglePattern2(); } return sp; } }
- 饿汉模式
public class SinglePattern1 { private SinglePattern1 sp = new SinglePattern1(); public SinglePattern1 getInstance() { return sp; } }
两种模式差别在有没有在类被加载时就给创建好对象,‘饿汉’ 即等不及了要吃东西所以要提前创建好对象,‘饱汉’正好相反
二、模板方法
给出算法的骨架,具体由实现类去实现。
public abstract class Account {
private int year;
private double fund;
public Account(int year, double fund) {
super();
this.year = year;
this.fund = fund;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public double getFund() {
return fund;
}
public void setFund(double fund) {
this.fund = fund;
}
// 具体账户计算所获得信息必须先实现该账户的利率
public double getInterest() {
return fund * getInterestRate();
}
public abstract double getInterestRate();
}
public class AccountA extends Account {
private static final double INTEREST = 0.03;
public AccountA(int year, double fund) {
super(year, fund);
}
@Override
public double getInterestRate() {
return super.getYear() * INTEREST;
}
}
public class Test {
public static void main(String[] args) {
AccountA a = new AccountA(3,20000);
System.out.println(a.getInterest());
}
}