单例设计模式
//单例 public class Student { private Student(){} private static Student instance = new Student(); public Student getInstance() { return instance; } }
组合设计模式
//组合 public class Coder { private Computer com; public Coder(Computer com) { this.com = com; } } public class Computer { }
模版方法设计模式
public class Test { /** *模板方法 */ public static void main(String[] args) { AbstractPrinter printer = new MyPrinter(); printer.run(); } } abstract class AbstractPrinter { public final void run() { open(); close(); } abstract void open(); abstract void close(); } class MyPrinter extends AbstractPrinter{ @Override void close() { System.out.println("close"); } @Override void open() { System.out.println("open"); } }
装饰设计模式
public class Test { /** * @param args */ public static void main(String[] args) { Man man = new Man(); SuperMan sm = new SuperMan(man); sm.eat(); } } class Man { public void eat() { System.out.println("eating!!!!"); } public void run() { System.out.println("running!!!!"); } } class SuperMan { private Man man; public SuperMan(Man man) { this.man = man; } public void eat() { System.out.println("lai yi bei"); man.eat(); System.out.println("lai yi gen"); } public void run() { man.run(); } public void fly() { System.out.println("fly"); } }
本文介绍了四种常用的设计模式:单例模式确保一个类只有一个实例;组合模式用于将对象组织到树形结构中以表现部分整体层次;模板方法模式定义了算法骨架,而将某些步骤延迟到子类中;装饰模式允许在不改变现有代码的情况下增加功能。
1488

被折叠的 条评论
为什么被折叠?



