设计模式(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(); } }