Java中单例模式定义:“一个类有且仅有一个实例,而且自行实例化向整个系统提供。” java
目的:是使内存中保持1个对象。 算法
单例模式三种经常使用形式: 数据库
第一种形式:懒汉式,也是经常使用的形式。 编程
public class SingletonClass{ private static SingletonClass instance=null; public static SingletonClass getInstance() { if(instance==null) { instance=new SingletonClass(); } return instance; } private SingletonClass(){ } }
第二种形式:饿汉式 设计模式
//对第一行static的一些解释 // java容许咱们在一个类里面定义静态类。好比内部类(nested class)。 //把nested class封闭起来的类叫外部类。 //在java中,咱们不能用static修饰顶级类(top level class)。 //只有内部类能够为static。 public static class Singleton{ //在本身内部定义本身的一个实例,只供内部调用 private static final Singleton instance = new Singleton(); private Singleton(){ //do something } //这里提供了一个供外部访问本class的静态方法,能够直接访问 public static Singleton getInstance(){ return instance; } }
第三种形式: 双重锁的形式。 数组
public static class Singleton{ private static Singleton instance=null; private Singleton(){ //do something } public static Singleton getInstance(){ if(instance==null){ synchronized(Singleton.class){ if(null==instance){ instance=new Singleton(); } } } return instance; } }
简单工厂模式是由一个工厂对象决定建立出哪种产品类的实例。 编程语言
Output,接口 测试
public interface Output { //接口里定义的属性只能是常量 intMAX_CACHE_LINE = 50; //接口里定义的只能是public的抽象实例方法 void out(); void getData(String msg); }
Printer,Output的一个实现 this
public class Printer implements Output { private String[] printData = new String[MAX_CACHE_LINE]; //用以记录当前需打印的做业数 private int dataNum = 0; public void out() { //只要还有做业,继续打印 while(dataNum > 0) { System.out.println("打印机打印:" + printData[0]); //把做业队列总体前移一位,并将剩下的做业数减1 System.arraycopy(printData , 1, printData, 0, --dataNum); } } public void getData(String msg) { if (dataNum >= MAX_CACHE_LINE) { System.out.println("输出队列已满,添加失败"); } else { //把打印数据添加到队列里,已保存数据的数量加1。 printData[dataNum++] = msg; } } }
BetterPrinter,Output的一个实现 spa
public class BetterPrinter implements Output { private String[] printData = new String[MAX_CACHE_LINE * 2]; //用以记录当前需打印的做业数 private int dataNum = 0; public void out() { //只要还有做业,继续打印 while(dataNum > 0) { System.out.println("高速打印机正在打印:" + printData[0]); //把做业队列总体前移一位,并将剩下的做业数减1 System.arraycopy(printData , 1, printData, 0, --dataNum); } } public void getData(String msg) { if (dataNum >= MAX_CACHE_LINE * 2) { System.out.println("输出队列已满,添加失败"); } else { //把打印数据添加到队列里,已保存数据的数量加1。 printData[dataNum++] = msg; } } }
OutputFactory,简单工厂类
public class Output{ public Output getPrinterOutput(String type) { if (type.equalsIgnoreCase("better")) { return new BetterPrinter(); } else { return new Printer(); } } }
public class Computer { private Output out; public Computer(Output out) { this.out = out; } //定义一个模拟获取字符串输入的方法 public void keyIn(String msg) { out.getData(msg); } //定义一个模拟打印的方法 public void print() { out.out(); } public static void main(String[] args) { //建立OutputFactory OutputFactory of = new OutputFactory(); //将Output对象传入,建立Computer对象 Computer c = new Computer(of.getPrinterOutput("normal")); c.keyIn("建筑永恒之道"); c.keyIn("建筑模式语言"); c.print(); c = new Computer(of.getPrinterOutput("better")); c.keyIn("建筑永恒之道"); c.keyIn("建筑模式语言"); c.print(); }
该模式其实就是说,一个对象的组成可能有不少其余的对象一块儿组成的,好比说,一个对象的实现很是复杂,有不少的属性,而这些属性又是其余对象的引用,可能这些对象的引用又包括不少的对象引用。封装这些复杂性,就可使用建造模式。
随着系统的不断改进和开发,它们会变得愈来愈复杂,系统会生成大量的类,这使得程序流程更难被理解。门面模式可为这些类提供一个简化的接口,从而简化访问这些类的复杂性。
门面模式(Facade)也被称为正面模式、外观模式,这种模式用于将一组复杂的类包装到一个简单的外部接口中。
原来的方式
// 依次建立三个部门实例 Payment pay = new PaymentImpl(); Cook cook = new CookImpl(); Waiter waiter = new WaiterImpl(); // 依次调用三个部门实例的方法来实现用餐功能 String food = pay.pay(); food = cook.cook(food); waiter.serve(food);
门面模式
public class Facade { // 定义被Facade封装的三个部门 Payment pay; Cook cook; Waiter waiter; // 构造器 public Facade() { this.pay = new PaymentImpl(); this.cook = new CookImpl(); this.waiter = new WaiterImpl(); } public void serveFood() { // 依次调用三个部门的方法,封装成一个serveFood()方法 String food = pay.pay(); food = cook.cook(food); waiter.serve(food); } }
门面模式调用
Facade f = new Facade(); f.serveFood();
策略模式用于封装系列的算法,这些算法一般被封装在一个被称为Context的类中,客户端程序能够自由选择其中一种算法,或让Context为客户端选择一种最佳算法——使用策略模式的优点是为了支持算法的自由切换。
public interface DiscountStrategy { //定义一个用于计算打折价的方法 double getDiscount(double originPrice); }
public class OldDiscount implements DiscountStrategy { // 重写getDiscount()方法,提供旧书打折算法 public double getDiscount(double originPrice) { System.out.println("使用旧书折扣..."); return originPrice * 0.7; } }
//实现DiscountStrategy接口,实现对VIP打折的算法 public class VipDiscount implements DiscountStrategy { // 重写getDiscount()方法,提供VIP打折算法 public double getDiscount(double originPrice) { System.out.println("使用VIP折扣..."); return originPrice * 0.5; } }
public class DiscountContext { //组合一个DiscountStrategy对象 private DiscountStrategy strategy; //构造器,传入一个DiscountStrategy对象 public DiscountContext(DiscountStrategy strategy) { this.strategy = strategy; } //根据实际所使用的DiscountStrategy对象获得折扣价 publicdouble getDiscountPrice(double price) { //若是strategy为null,系统自动选择OldDiscount类 if (strategy == null) { strategy = new OldDiscount(); } return this.strategy.getDiscount(price); } //提供切换算法的方法 publicvoid setDiscount(DiscountStrategy strategy) { this.strategy = strategy; } }
public static void main(String[] args) { //客户端没有选择打折策略类 DiscountContext dc = new DiscountContext(null); double price1 = 79; //使用默认的打折策略 System.out.println("79元的书默认打折后的价格是:" + dc.getDiscountPrice(price1)); //客户端选择合适的VIP打折策略 dc.setDiscount(new VipDiscount()); double price2 = 89; //使用VIP打折获得打折价格 System.out.println("89元的书对VIP用户的价格是:" + dc.getDiscountPrice(price2)); }
观察者模式定义了对象间的一对多依赖关系,让一个或多个观察者对象观察一个主题对象。当主题对象的状态发生变化时,系统能通知全部的依赖于此对象的观察者对象,从而使得观察者对象可以自动更新。
观察者:观察者也是一个接口,该接口规定了具体观察者用来更新数据的方法.
public interface Observer { void update(Observable o, Object arg); }
主题:主题是一个接口,该接口规定了具体主题须要实现的方法,好比添加、删除观察者以及通知观察者更新数据的方法
import java.util.ArrayList; import java.util.List; import java.util.Iterator; public abstract class Observable { // 用一个List来保存该对象上全部绑定的事件监听器 List<Observer> observers = new ArrayList<Observer>(); // 定义一个方法,用于从该主题上注册观察者 public void registObserver(Observer o) { observers.add(o); } // 定义一个方法,用于从该主题中删除观察者 public void removeObserver(Observer o) { observers.add(o); // 通知该主题上注册的全部观察者 public void notifyObservers(Object value) { // 遍历注册到该被观察者上的全部观察者 for (Iterator it = observers.iterator(); it.hasNext();) { Observer o = (Observer) it.next(); // 显式每一个观察者的update方法 o.update(this, value); } } }
具体主题:具体主题是一个实现主题接口的类,该类包含了会常常发生变化的数据。并且还有一个集合,该集合存放的是观察者的引用。
public class Product extends Observable { // 定义两个属性 private String name; private double price; // 无参数的构造器 public Product() { } public Product(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } // 当程序调用name的setter方法来修改Product的name属性时 // 程序天然触发该对象上注册的全部观察者 public void setName(String name) { this.name = name; notifyObservers(name); } public double getPrice() { return price; } // 当程序调用price的setter方法来修改Product的price属性时 // 程序天然触发该对象上注册的全部观察者 public void setPrice(double price) { this.price = price; notifyObservers(price); } }
具体观察者:具体观察者是实现了观察者接口的一个类。具体观察者包含有能够存放具体主题引用的主题接口变量,以便具体观察者让具体主题将本身的引用添加到具体主题的集合中,让本身成为它的观察者,或者让这个具体主题将本身从具体主题的集合中删除,使本身不在时它的观察者.
import javax.swing.JFrame; import javax.swing.JLabel; public class NameObserver implements Observer { // 实现观察者必须实现的update方法 public void update(Observable o, Object arg) { if (arg instanceof String) { // 产品名称改变值在name中 String name = (String) arg; // 启动一个JFrame窗口来显示被观察对象的状态改变 JFrame f = new JFrame("观察者"); JLabel l = new JLabel("名称改变为:" + name); f.add(l); f.pack(); f.setVisible(true); System.out.println("名称观察者:" + o + "物品名称已经改变为: " + name); } } }
public class PriceObserver implements Observer { // 实现观察者必须实现的update方法 public void update(Observable o, Object arg) { if (arg instanceof Double) { System.out.println("价格观察者:" + o + "物品价格已经改变为: " + arg); } } }
测试:
public class Test { public static void main(String[] args) { // 建立一个被观察者对象 Product p = new Product("电视机", 176); // 建立两个观察者对象 NameObserver no = new NameObserver(); PriceObserver po = new PriceObserver(); // 向被观察对象上注册两个观察者对象 p.registObserver(no); p.registObserver(po); // 程序调用setter方法来改变Product的name和price属性 p.setName("书桌"); p.setPrice(345f); } }
代理模式是一种应用很是普遍的设计模式,当客户端代码须要调用某个对象时,客户端实际上不关心是否准确获得该对象,它只要一个能提供该功能的对象便可,此时咱们就可返回该对象的代理(Proxy)。
代理就是一个Java对象表明另外一个Java对象来采起行动。如:
public class ImageProxy implements Image { //组合一个image实例,做为被代理的对象 private Image image; //使用抽象实体来初始化代理对象 public ImageProxy(Image image) { this.image = image; } /** * 重写Image接口的show()方法 * 该方法用于控制对被代理对象的访问, * 并根据须要负责建立和删除被代理对象 */ public void show() { //只有当真正须要调用image的show方法时才建立被代理对象 if (image == null) { image = new BigImage(); } image.show(); } }
如:Hibernate默认启用延迟加载,当系统加载A实体时,A实体关联的B实体并未被加载出来,A实体所关联的B实体所有是代理对象——只有等到A实体真正须要访问B实体时,系统才会去数据库里抓取B实体所对应的记录。
某个方法须要完成某一个功能,完成这个功能的大部分步骤已经肯定了,但可能有少许具体步骤没法肯定,必须等到执行该方法时才能够肯定。(在某些编程语言如Ruby、Perl里,容许传入一个代码块做为参数。但Jara暂时还不支持代码块做为参数)。
在Java中,传入该方法的是一个对象,该对象一般是某个接口的匿名实现类的实例,该接口一般被称为命令接口,这种设计方式也被称为命令模式。
public interface Command { //接口里定义的process方法用于封装“处理行为” void process(int[] target); }
public class ProcessArray { //定义一个each()方法,用于处理数组, publicv oid each(int[] target , Command cmd) { cmd.process(target); } }
public class TestCommand { public static void main(String[] args) { ProcessArray pa = new ProcessArray(); int[] target = {3, -4, 6, 4}; //第一次处理数组,具体处理行为取决于Command对象 pa.each(target , new Command() { //重写process()方法,决定具体的处理行为 public void process(int[] target) { for (int tmp : target ) { System.out.println("迭代输出目标数组的元素:" + tmp); } } }); System.out.println("------------------"); //第二次处理数组,具体处理行为取决于Command对象 pa.each(target , new Command() { //重写process方法,决定具体的处理行为 public void process(int[] target) { int sum = 0; for (int tmp : target ) { sum += tmp; } System.out.println("数组元素的总和是:" + sum); } }); } }
因为实际的须要,某个类具备两个以上的维度变化,若是只是使用继承将没法实现这种须要,或者使得设计变得至关臃肿。而桥接模式的作法是把变化部分抽象出来,使变化部分与主类分离开来,从而将多个的变化完全分离。最后提供一个管理类来组合不一样维度上的变化,经过这种组合来知足业务的须要。
Peppery口味风格接口:
public interface Peppery { String style(); }
口味之一
public class PepperySytle implements Peppery { //实现"辣味"风格的方法 public String style() { return"辣味很重,很过瘾..."; } }
口味之二
public class PlainStyle implements Peppery { //实现"不辣"风格的方法 public String style() { return"味道清淡,很养胃..."; } }
口味的桥梁
public abstract class AbstractNoodle { //组合一个Peppery变量,用于将该维度的变化独立出来 protected Peppery style; //每份Noodle必须组合一个Peppery对象 public AbstractNoodle(Peppery style) { this.style = style; } public abstract void eat(); }
材料之一,继承口味
public class PorkyNoodle extends AbstractNoodle { public PorkyNoodle(Peppery style) { super(style); } //实现eat()抽象方法 public void eat() { System.out.println("这是一碗稍嫌油腻的猪肉面条。" + super.style.style()); } }
材料之二,继承口味
public class BeefMoodle extends AbstractNoodle { public BeefMoodle(Peppery style) { super(style); } //实现eat()抽象方法 public void eat() { System.out.println("这是一碗美味的牛肉面条。" + super.style.style()); } }
主程序
public class Test { public static void main(String[] args) { //下面将获得“辣味”的牛肉面 AbstractNoodle noodle1 = new BeefMoodle( new PepperySytle()); noodle1.eat(); //下面将获得“不辣”的牛肉面 AbstractNoodle noodle2 = new BeefMoodle( new PlainStyle()); noodle2.eat(); //下面将获得“辣味”的猪肉面 AbstractNoodle noodle3 = new PorkyNoodle( new PepperySytle()); noodle3.eat(); //下面将获得“不辣”的猪肉面 AbstractNoodle noodle4 = new PorkyNoodle( new PlainStyle()); noodle4.eat(); } }