java几种简单的设计模式
单例设计模式
//单例 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"); } }