設計模式(Design pattern)是一套被反覆使用、多數人知曉的、通過分類編目的、代碼設計經驗的總結。使用設計模式是爲了可重用代碼、讓代碼更容易被他人理解、保證代碼可靠性。 毫無疑問,設計模式於己於他人於系統都是多贏的,設計模式使代碼編制真正工程化,設計模式是軟件工程的基石,如同大廈的一塊塊磚石同樣。項目中合理的運用設計模式能夠完美的解決不少問題,每種模式在如今中都有相應的原理來與之對應,每個模式描述了一個在咱們周圍不斷重複發生的問題,以及該問題的核心解決方案,這也是它能被普遍應用的緣由。簡單說:程序員
模式:在某些場景下,針對某類問題的某種通用的解決方案。算法
整體來講設計模式分爲三大類:編程
用一個圖片來總體描述一下:設計模式
單例模式 安全
public class LazySingleton { private static volatile LazySingleton instance = null; //保證 instance 在全部線程中同步 private LazySingleton() {} //private 避免類在外部被實例化 public static synchronized LazySingleton getInstance() { //getInstance 方法前加同步 if(instance == null) { instance = new LazySingleton(); } return instance; } }
public class HungrySingleton { private static final HungrySingleton instance = new HungrySingleton(); private HungrySingleton(){} public static HungrySingleton getInstance() { return instance; } }
public interface Product { public void show(); } public class ConcreteProduct1 implements Product { public void show() { System.out.println("具體產品1顯示...."); } } public class ConcreteProduct2 implements Product { public void show() { System.out.println("具體產品1顯示...."); } } public interface AbstractFactory { public Product newProduct(); } public class ConcreteFactory1 implements AbstractFactory { public Product newProduct() { System.out.println("具體工廠1生成-->具體產品1..."); return new ConcreteProduct1(); } } public class ConcreteFactory2 implements AbstractFactory { public Product newProduct() { System.out.println("具體工廠2生成-->具體產品2..."); return new ConcreteProduct2(); } } public class AbstractFactoryTest { public static void main(String[] args) { try { Class<?> c = Class.forName("com.lynn.learning.designPattern.factoryMethod.ConcreteFactory2"); AbstractFactory af = (AbstractFactory) c.newInstance(); Product a = af.newProduct(); a.show(); } catch(Exception e) { e.printStackTrace(); } } }
public interface Animal { public void show(); } public class Cattle implements Animal { JScrollPane sp; JFrame jf = new JFrame("抽象工廠模式測試"); public Cattle() { Container contentPane=jf.getContentPane(); JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(1,1)); p1.setBorder(BorderFactory.createTitledBorder("動物:牛")); sp = new JScrollPane(p1); contentPane.add(sp, BorderLayout.CENTER); JLabel l1 = new JLabel(new ImageIcon("src/com/lynn/learning/designPattern/abstractFactory/A_Cattle.jpg")); p1.add(l1); jf.pack(); jf.setVisible(false); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//用戶點擊窗口關閉 } public void show() { jf.setVisible(true); } } public class Horse implements Animal { JScrollPane sp; JFrame jf = new JFrame("抽象工廠模式測試"); public Horse() { Container contentPane = jf.getContentPane(); JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(1,1)); p1.setBorder(BorderFactory.createTitledBorder("動物:馬")); sp = new JScrollPane(p1); contentPane.add(sp, BorderLayout.CENTER); JLabel l1 = new JLabel(new ImageIcon("src/com/lynn/learning/designPattern/abstractFactory/A_Horse.jpg")); p1.add(l1); jf.pack(); jf.setVisible(false); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//用戶點擊窗口關閉 } public void show() { jf.setVisible(true); } } public interface Farm { public Animal newAnimal(); public Plant newPlant(); } public class Fruitage implements Plant { JScrollPane sp; JFrame jf = new JFrame("抽象工廠模式測試"); public Fruitage() { Container contentPane = jf.getContentPane(); JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(1,1)); p1.setBorder(BorderFactory.createTitledBorder("植物:水果")); sp = new JScrollPane(p1); contentPane.add(sp, BorderLayout.CENTER); JLabel l1 = new JLabel(new ImageIcon("src/com/lynn/learning/designPattern/abstractFactory/P_Vegetables.jpg")); p1.add(l1); jf.pack(); jf.setVisible(false); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//用戶點擊窗口關閉 } public void show() { jf.setVisible(true); } } public class Vegetables implements Plant { JScrollPane sp; JFrame jf = new JFrame("抽象工廠模式測試"); public Vegetables() { Container contentPane = jf.getContentPane(); JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(1, 1)); p1.setBorder(BorderFactory.createTitledBorder("植物:蔬菜")); sp = new JScrollPane(p1); contentPane.add(sp, BorderLayout.CENTER); JLabel l1 = new JLabel(new ImageIcon("src/com/lynn/learning/designPattern/abstractFactory/P_Vegetables.jpg")); p1.add(l1); jf.pack(); jf.setVisible(false); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//用戶點擊窗口關閉 } public void show() { jf.setVisible(true); } } public class SGfarm implements Farm { public Animal newAnimal() { System.out.println("新牛出生!"); return new Cattle(); } public Plant newPlant() { System.out.println("蔬菜長成!"); return new Vegetables(); } } public class SRfarm implements Farm { public Animal newAnimal() { System.out.println("新馬出生!"); return new Horse(); } public Plant newPlant() { System.out.println("水果長成!"); return new Fruitage(); } } public class FarmTest { public static void main(String[] args) { try { Class<?> c = Class.forName("com.lynn.learning.designPattern.abstractFactory.SGfarm"); Farm f = (Farm) c.newInstance(); Animal a = f.newAnimal(); Plant p = f.newPlant(); a.show(); p.show(); } catch(Exception e) { e.printStackTrace(); } } }
public interface Shape extends Cloneable { public Object clone(); //拷貝 public void countArea(); //計算面積 } public class Square implements Shape { private Scanner input; public Object clone() { Square b = null; try { b = (Square)super.clone(); } catch(CloneNotSupportedException e) { System.out.println("拷貝正方形失敗!"); } return b; } public void countArea() { int a = 0; System.out.print("這是一個正方形,請輸入它的邊長:"); input = new Scanner(System.in); a=input.nextInt(); System.out.print("該正方形的面積=" + a * a + "\n"); } } public class Circle implements Shape { private Scanner input; public Object clone() { Circle w = null; try { w = (Circle)super.clone(); } catch(CloneNotSupportedException e) { System.out.println("拷貝圓失敗!"); } return w; } public void countArea() { int r=0; System.out.print("這是一個圓,請輸入圓的半徑:"); input = new Scanner(System.in); r = input.nextInt(); System.out.println("該圓的面積=" + 3.1415 * r * r + "\n"); } } public class ProtoTypeManager { private HashMap<String, Shape> ht = new HashMap<String,Shape>(); public ProtoTypeManager() { ht.put("Circle", new Circle()); ht.put("Square", new Square()); } public void addshape(String key, Shape obj) { ht.put(key, obj); } public Shape getShape(String key) { Shape temp = ht.get(key); return (Shape) temp.clone(); } } public class ProtoTypeShape { public static void main(String[] args) { ProtoTypeManager pm = new ProtoTypeManager(); Shape obj1 = (Circle)pm.getShape("Circle"); obj1.countArea(); Shape obj2 = (Shape)pm.getShape("Square"); obj2.countArea(); } }
public interface Target { public void request(); } public class Adaptee { public void specificRequest() { System.out.println("適配者中的業務代碼被調用!"); } } public class ClassAdapter extends Adaptee implements Target { public void request() { specificRequest(); } } public class ClassAdapterTest { public static void main(String[] args) { System.out.println("類適配器模式測試:"); Target target = new ClassAdapter(); target.request(); } }
public interface Target { public void request(); } public class Adaptee { public void specificRequest() { System.out.println("適配者中的業務代碼被調用!"); } } public class ObjectAdapter implements Target { private Adaptee adaptee; public ObjectAdapter(Adaptee adaptee) { this.adaptee = adaptee; } public void request() { adaptee.specificRequest(); } } public class ObjectAdapterTest { public static void main(String[] args) { System.out.println("對象適配器模式測試:"); Adaptee adaptee = new Adaptee(); Target target = new ObjectAdapter(adaptee); target.request(); } }
public interface Implementor { public void OperationImpl(); } public class ConcreteImplementorA implements Implementor { public void OperationImpl() { System.out.println("具體實現化(Concrete Implementor)角色被訪問" ); } } public abstract class Abstraction { protected Implementor imple; protected Abstraction(Implementor imple) { this.imple = imple; } public abstract void Operation(); } public class RefinedAbstraction extends Abstraction{ protected RefinedAbstraction(Implementor imple) { super(imple); } public void Operation() { System.out.println("擴展抽象化(Refined Abstraction)角色被訪問" ); imple.OperationImpl(); } } public class BridgeTest { public static void main(String[] args) { Implementor imple = new ConcreteImplementorA(); Abstraction abs = new RefinedAbstraction(imple); abs.Operation(); } }
public interface Component { public void add(Component c); public void remove(Component c); public Component getChild(int i); public void operation(); } public class Leaf implements Component { private String name; public Leaf(String name) { this.name = name; } public void add(Component c) { } public void remove(Component c) { } public Component getChild(int i) { return null; } public void operation() { System.out.println("樹葉" + name + ":被訪問!"); } } public class Composite implements Component { private ArrayList<Component> children = new ArrayList<Component>(); public void add(Component c) { children.add(c); } public void remove(Component c) { children.remove(c); } public Component getChild(int i) { return children.get(i); } public void operation() { for(Object obj : children) { ((Component)obj).operation(); } } } public class CompositePattern { public static void main(String[] args) { Component c0 = new Composite(); Component c1 = new Composite(); Component leaf1 = new Leaf("1"); Component leaf2 = new Leaf("2"); Component leaf3 = new Leaf("3"); c0.add(leaf1); c0.add(c1); c1.add(leaf2); c1.add(leaf3); c0.operation(); } }
public interface Component { public void operation(); } public class ConcreteComponent implements Component{ public ConcreteComponent() { System.out.println("建立具體構件角色"); } public void operation() { System.out.println("調用具體構件角色的方法operation()"); } } public class Decorator implements Component { private Component component; public Decorator(Component component) { this.component = component; } public void operation() { component.operation(); } } public class ConcreteDecorator extends Decorator { public ConcreteDecorator(Component component) { super(component); } public void operation() { super.operation(); addedFunction(); } public void addedFunction() { System.out.println("爲具體構件角色增長額外的功能addedFunction()"); } } public class DecoratorPattern { public static void main(String[] args) { Component p = new ConcreteComponent(); p.operation(); System.out.println("---------------------------------"); Component d = new ConcreteDecorator(p); d.operation(); } }