1、装饰器模式
允许向一个现有的对象添加新的功能,同时又不改变其结构。
- 抽象对象
public interface Hero {
void learnSkills();
}
- 某类对象
class BlindMonk implements Hero {
private String name;
public BlindMonk(String name) {
this.name = name;
}
@Override
public void learnSkills() {
System.out.println(name + "学习了以上技能!");
}
}
- 抽象对象具有操作及装饰
//Decorator 技能栏:装饰类
class Skills implements Hero{
//持有一个英雄对象接口
private Hero hero;
public Skills(Hero hero) {
this.hero = hero;
}
@Override
public void learnSkills() {
if(hero != null)
hero.learnSkills();
}
}
//ConreteDecorator 技能:R
class Skill_R extends Skills{
private String skillName;
public Skill_R(Hero hero,String skillName) {
//装饰父类对象
super(hero);
this.skillName = skillName;
}
@Override
public void learnSkills() {
System.out.println("学习了技能R:" +skillName );
//装饰父类方法
super.learnSkills();
}
}
- 测试
public class Test1{
public static void main(String[] args) {
Hero hero = new BlindMonk("李青");
Skills skills = new Skills(hero);
Skills r = new Skill_R(skills,"猛龙摆尾");
r.learnSkills();
}
}
2、 单例模式
- 懒汉式,非线程安全
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
- 懒汉式, 线程安全
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
- 饿汉式
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}
- 双重校验锁
public class Singleton {
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
- 静态内部类
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}