各种设计模式的应用实例


各种设计模式的应用实例_第1张图片

两年前学设计模式总结的小李子,扔了可惜,挂这儿权当作纪念吧。

    • Bridge设计模式
        • 画图形的故事
        • 毛笔与蜡笔的故事
    • Adapter设计模式
    • Singleton和Double-Checked Locking设计模式
      • Singleton模式
      • Double-Checked Locking模式
    • Observer设计模式
        • 例子1
        • 例子2
    • Decorator设计模式
        • 发票的故事
        • 汉堡的故事
        • Java IO流的设计模式
    • Facade设计模式
        • 创建更简单的接口
        • 减少必须处理的对象数量
    • Abstract Factory设计模式
    • Factory Method设计模式
    • Strategy设计模式
    • Template Method设计模式
    • Object Pool设计模式
        • 代码1
        • 代码2
    • Iterator设计模式

Bridge设计模式

画图形的故事

Bridge设计模式图:

代码:

package bupt.xujinliang.bridgepattern;
/** * * @author jin * */
public class BridgeExample {
    public static void main(String[] args) {
        Shape myRetangle,myCircle;
        myRetangle= new Retangle(new V1Drawing());
        myRetangle.draw();
        myRetangle.setDrawing(new V2Drawing());
        myRetangle.draw();
        myCircle = new Circle(new V1Drawing());
        myCircle.draw();
        myCircle.setDrawing(new V2Drawing());
        myCircle.draw();
    }
}
abstract  class Shape {
    protected Drawing myDrawing;
    abstract public void draw();
    abstract public void setDrawing(Drawing myDrawing);
    Shape(Drawing drawing) {
        myDrawing = drawing;
    }
}
class Retangle extends Shape {
    public Retangle(Drawing drawing) {
        super(drawing);
    }
    public void setDrawing(Drawing myDrawing) {
        this.myDrawing = myDrawing;
    }
    public void draw() {
        myDrawing.drawRetangle();
    }
}
class Circle extends Shape {
    public Circle(Drawing drawing) {
        super(drawing);
    }
    public void setDrawing(Drawing myDrawing) {
        this.myDrawing = myDrawing;
    }
    public void draw() {
        myDrawing.drawCircle(); 
    }   
}
abstract  class Drawing {
    abstract public void drawRetangle();
    abstract public void drawCircle();
}
class V1Drawing extends Drawing {
    public void drawRetangle() {
        System.out.println("V1Drawing draw a retangle");
    }
    public void drawCircle() {
        System.out.println("V1Drawing draw a circle");
    }   
}
class V2Drawing extends Drawing {
    public void drawRetangle() {
        System.out.println("V2Drawing draw a retangle");
    }
    public void drawCircle() {
        System.out.println("V2Drawing draw a circle");
    }   
}

毛笔与蜡笔的故事

UML图:
各种设计模式的应用实例_第2张图片

代码:

package bupt.xujinliang.bridgepattern;
/** * * @author jin * */
public class BrushExample {
    public static void main(String[] args) {
        Brush bigBrush,midBrush,smallBrush;
        bigBrush = new BigBrush(new BlueColor());
        midBrush = new MidBrush(new BlueColor());
        smallBrush = new SmallBrush(new BlueColor());
        bigBrush.paint();
        midBrush.paint();
        smallBrush.paint();
        bigBrush.SetColor(new RedColor());
        midBrush.SetColor(new RedColor());
        smallBrush.SetColor(new RedColor());
        bigBrush.paint();
        midBrush.paint();
        smallBrush.paint();
        bigBrush.SetColor(new YellowColor());
        midBrush.SetColor(new YellowColor());
        smallBrush.SetColor(new YellowColor());
        bigBrush.paint();
        midBrush.paint();
        smallBrush.paint();
        bigBrush.SetColor(new PinkColor());
        midBrush.SetColor(new PinkColor());
        smallBrush.SetColor(new PinkColor());
        bigBrush.paint();
        midBrush.paint();
        smallBrush.paint();     
    }
}
abstract class Color {
    private String color;
    public String getColor() {
        return color;
    }
    public Color(String color) {
        this.color = color;
    }
}
class RedColor extends Color {  
    public RedColor() {
        super("Red");
    }   
}
class BlueColor extends Color { 
    public BlueColor() {
        super("Blue");
    }   
}
class YellowColor extends Color {   
    public YellowColor() {
        super("Yellow");
    }   
}
class PinkColor extends Color { 
    public PinkColor() {
        super("Pink");
    }   
}
abstract class Brush {
    protected Color color;
    public abstract void paint();
    public Brush(Color color) {
        this.color = color;
    }
    public void SetColor(Color color)
    { 
        this.color = color; 
    }
}
class BigBrush extends Brush {
    public BigBrush(Color color) {
        super(color);
    }
    public void paint() {
        System.out.println("BigBrush:"+color.getColor());
    }   
}
class MidBrush extends Brush {
    public MidBrush(Color color) {
        super(color);
    }
    public void paint() {
        System.out.println("MidBrush:"+color.getColor());
    }   
}
class SmallBrush extends Brush {
    public SmallBrush(Color color) {
        super(color);
    }
    public void paint() {
        System.out.println("SmallBrush:"+color.getColor());
    }   
}

运行结果:
各种设计模式的应用实例_第3张图片

Adapter设计模式

UML图
各种设计模式的应用实例_第4张图片

package bupt.xujinliang.adapterpattern;
/** * * @author jin * */
public class AdapterExample {
    public static void main(String[] args) {
        MyDrawingSystem myDrawing = new MyDrawingSystem();
        myDrawing.drawLine();
        myDrawing.drawCircle();
    }

}
class MyDrawingSystem {
    private DrawSystem_Other drawing;
    public MyDrawingSystem () {
        drawing = new DrawSystem_Other();
    }
    public void drawLine() {
        drawing.draw_a_line();  
    }
    public void drawCircle() {
        drawing.draw_a_circle();
    }   
}
class DrawSystem_Other {
    public void draw_a_line() {
        System.out.println("draw a line");
    };
    public void draw_a_circle() {
        System.out.println("draw a circle");
    };
}

Singleton和Double-Checked Locking设计模式

Singleton模式

UML图:
各种设计模式的应用实例_第5张图片

代码:

package bupt.xujinliang.singletonpattern;
/** * * @author jin * */
public class SingletonExample {
    public static void main(String[] args) {
        Printer printer1 = Printer.getInstance();
        Printer printer2 = Printer.getInstance();
        if(printer1 == printer2) {
            System.out.println("printer2 point to the same address with printer1");
        } else {
            System.out.println("printer2 point to different address with printer1");
        }
    }
}
class Printer {
    private static Printer instance;
    public Printer() {
        System.out.println("Printer Constructor");
    }   
    public static Printer getInstance() {
        if(null == instance) 
            instance = new Printer();
        return instance;
    }
}

运行结果:
各种设计模式的应用实例_第6张图片

Double-Checked Locking模式

Double Check Locking模式是singleton的多线程版本,必须使用锁来锁定临界区,当多个线程存在访问临界区的意图时,保证了临界区只被访问一次。
首先介绍其在C/C++环境下的实现过程:
代码1:

Printer* get_instance(void)
{
    lock();
    if( instance == 0) {
       instance = new Printer;
    }
    unlock();
    return instance;
}

上述代码存在的问题是:无论是否已经初始化都要加锁,增加了负荷,已经没有所谓的并发性能了。
代码2:

Printer* get_instance(void)
{ 
    if( instance == 0){
        lock();
        instance = new Printer;
        unlock();
    }
    return instance;
}

上述代码存在的问题是:不能保证临界区只初始化一次,没能实现singleton的基本功能。
代码3:

Printer* get_instance(void)
{ 
    if( instance == 0){
        lock();
        if( instance == 0 )
 instance = new Printer; unlock(); } return instance; }

这是比较完善的Double-Checked Locking模式实现的代码。
为什么叫做Double-Checked Locking呢?请看上述代码3,可以看到在加锁前后都对instance变量进行了检查,故谓之Double-Checked Locking。
那么在Java中的实现与在C/C++中不同吗?是的。
下面的的Java代码是不能够实现Double-Checked Locking模式的:

class Printer {
    private static Printer resource ;
    public static Printer getInstance(){    
        if(resource == null ){
            synchronized (DoubleCheckedLockingExample.class) {
                if(resource  == null ){
                    resource  = new Printer() ;
                }
            }           
        }       
        return resource ;
    }   
    private Printer(){}
}

上面程序真正的问题是没有同步的情况下读取共享变量resource,并发的情况下对象的状态值有可能是过期无效的。要解决这个问题也很简单,把resource声明为volatile类型。volatile有什么作用?引用《java并发编程实战》的解析:
当一个域声明为volatile类型后,编译器与运行时会监视这个变量:它是共享的,而且对它的操作不会与其他的内存操作一起被重排序。volatile变量不会缓存在寄存器或缓存在对其他处理器隐藏的地方。所以,读一个volatile类型的变量时,总会返回由某一线程所写入的最新值。
读取volatile变量比读取非volatile变量的性能几乎没有差别,不过需要注意的是volatile只能保证内存可见性,并不能保证原子性。
现给出Java在多线程下实现单个实例化对象的方法:

class Printer {
    private static class Instance {
        static final Printer instance = new Printer();
    }
    private static Printer resource ;
    public static Printer getInstance(){        
        return Instance.instance;
    }   
    private Printer(){}
}

上述方法之所以有效,是因为内部类(Instance)将只被装载一次,所以只会创建一个对象。

Observer设计模式

例子1

UML图:
各种设计模式的应用实例_第7张图片

代码:

package bupt.xujinliang.observerpattern;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;

public class Client {
    public static void main(String[] args) {
        NumberGenerator generator = new NumberGenerator();
        generator.add(new NumberObserver());
        generator.add(new SymbolObserver());    
        generator.begin();
    }
}
class NumberGenerator {
    private ArrayList observers = new ArrayList();
    private Random random = new Random();
    private int number;
    public void add(Observer o) {
        observers.add(o);
    }
    public void remove(Observer o) {
        observers.remove(o);
    }
    public void notifyObj() {
        Iterator it = observers.iterator();
        while(it.hasNext()) {
            Observer o =(Observer) it.next();
            o.update(this);
        }
    }
    public void begin() {
        for(int i=0 ; i < 5; i++) {
            number = random.nextInt(10);
            notifyObj();
        }
    }
    public int getNumber() {
        return number;
    } 
} 
interface Observer {
    public abstract void update(NumberGenerator generator);
}
class NumberObserver implements Observer{
    public void update(NumberGenerator generator) {
        System.out.println("NumberObserver: "+ generator.getNumber());
    }   
}
class SymbolObserver implements Observer{
    public void update(NumberGenerator generator) {
        System.out.print("SymbolObserver: ");
        int count = generator.getNumber();
        for(int i = 0 ; i < count; i ++) {  
            System.out.print("*");  
        } 
        System.out.println("");
    }
}

运行结果:
各种设计模式的应用实例_第8张图片

例子2

UML图:
各种设计模式的应用实例_第9张图片

代码:

package bupt.xujinliang.observerpattern;

import java.util.Observable;
import java.util.Observer;


public class Test {
      public static void main(String[] args){
              ProductControl productControl=new ProductControl();
              NameObserver nameobs=new NameObserver();
              PriceObserver priceobs = new PriceObserver();
              Product product = new Product();
              productControl.setProduct(product);
              productControl.register(priceobs,nameobs);
              product.setName("橘子");
              product.setPrice(1.22f);
      }
}

 class NameObserver implements Observer{
     private String name = "";
    public void update(Observable obj, Object arg) {
        // TODO Auto-generated method stub
         if(arg instanceof String){
             name=(String)arg;
             System.out.println("NameObserver :name changet to "+name);
         }  
    }
}

class PriceObserver implements Observer{
      private float price = 0;
      public void update(Observable obj, Object arg) {
         if (arg instanceof Float) {
            price = ((Float) arg).floatValue();
            System.out.println("PriceObserver:price changet to "+ price);
        }
     }
 }
class Product extends Observable{
    private String name;
    private float price;
    public String getName() {
           return name;
    }
   public void setName(String name) {
        this.name = name;
        setChanged();
        notifyObservers(name);
   }
   public float getPrice() {
       return price;
   }
   public void setPrice(float price) {
       this.price=price;
       setChanged();
       notifyObservers(new Float(price));
   }
}
class ProductControl{
     private Product product;
     public void setProduct(Product product){
            this.product = product;
     }
     public void register(PriceObserver priceObsv,NameObserver nameObsv){
           //加入观察者
         product.addObserver(priceObsv);
         product.addObserver(nameObsv);
     }
     public void removeNameObserver(PriceObserver priceObsv){
         product.deleteObserver(priceObsv);
     }
     public void removePriceObserver(NameObserver nameObsv){
        product.deleteObserver(nameObsv);
     }
}

程序运行结果:
这里写图片描述

Decorator设计模式

发票的故事

UML图:

代码:

package bupt.xujinliang.decoratorpattern;
/** * * @author jin * */
public class DecoratorExample {
    public static void main(String[] args) {
        Component myComponent;
        myComponent = new Header1(new Footer1(new SalesTicket()));
        myComponent.prtTicket();
    }
}
abstract class Component {
    abstract public void prtTicket();
}
class SalesTicket extends Component {
    public void prtTicket() {
        System.out.println("SALES TICKET");
    }
}
abstract class TicketDecorator extends Component {
    private Component myTrailer;
    public TicketDecorator (Component myComponent) {
        myTrailer = myComponent;
    }
    public void callTrailer() {
        if(null != myTrailer) 
            myTrailer.prtTicket();
    }
}
class Header1 extends TicketDecorator {
    public Header1 (Component myComponent) {
        super(myComponent);
    }
    public void prtTicket() {
        System.out.println("HEADER 1");
        super.callTrailer();
    }
}
class Header2 extends TicketDecorator {
    public Header2(Component myComponent) {
        super(myComponent);
    }
    public void prtTicket() {
        System.out.println("HEADER 2");
        super.callTrailer();
    }   
}
class Footer1 extends TicketDecorator {
    public Footer1(Component myComponent) {
        super(myComponent);
    }
    public void prtTicket() {
        super.callTrailer();
        System.out.println("FOOTER 1");
    }
}
class Footer2 extends TicketDecorator {
    public Footer2(Component myComponent) {
        super(myComponent);
    }
    public void prtTicket() {
        super.callTrailer();
        System.out.println("FOOTER 2");
    }
}

运行结果:
各种设计模式的应用实例_第10张图片

汉堡的故事

UML图:
各种设计模式的应用实例_第11张图片

代码:

package bupt.xujinliang.decoratorpattern;
/** * @author jin * */
public class HumburgerDecorator {
    public static void main(String[] args) {
        Chilli chilli = new Chilli(new Lettuce(new ChickenBurger()));
        System.out.println(chilli.getName()+" 价钱:"+chilli.getPrice());
    }


}

abstract class Humburger {       
    protected  String name ;     
    public String getName(){  
        return name;  
    }    
    public abstract double getPrice();  
}  
class ChickenBurger extends Humburger {      
    public ChickenBurger(){  
        name = "鸡腿堡";  
    }  
    @Override  
    public double getPrice() {  
        return 10;  
    }  
}  
abstract class Condiment extends Humburger {   
    public abstract String getName();  

}
class Lettuce extends Condiment {     
    Humburger humburger;      
    public Lettuce(Humburger humburger){  
        this.humburger = humburger;  
    }  
    @Override  
    public String getName() {  
        return humburger.getName()+" 加生菜";  
    }  
    @Override  
    public double getPrice() {  
        return humburger.getPrice()+1.5;  
    }  
}  
class Chilli extends Condiment {    
    Humburger humburger;
    public Chilli(Humburger humburger){
        this.humburger = humburger; 
    }
    @Override
    public String getName() {
        return humburger.getName()+" 加辣椒";
    }
    @Override
    public double getPrice() {
        return humburger.getPrice();  
    }
}

运行结果:

鸡腿堡 加生菜 加辣椒 价钱:11.5

Java IO流的设计模式

Java因其令人迷惑的各种流输入及相关的类而臭名昭著。在Decorator模式的背景下,理解这些类要容易得多。这些类直接派生自java.io.InputStream(ByteArrayInputStream、FileInputStream、InputSteam、FilterInputStream、SequenceInputStream、StringBufferInputStream、ObjectInputStream),都扮演被装饰对象的角色。所有的装饰都(直接或间接地)派生自FilterInputStream。
理解了Decorator模式,就可以解释为什么Java要求这些对象一个封装在另一个里——这使程序员能够从不同的行为中选取任意数量的组合。
下图是Java的输入流的类层次图:
各种设计模式的应用实例_第12张图片

JDK1.7关于FilterInputStream类的部分源码,如下,其展示了装饰者模式:

public class FilterInputStream extends InputStream {
     protected volatile InputStream in;
        protected FilterInputStream(InputStream in) {
        this.in = in;
        }
        //........ 
}

上述代码可由下图表示:
各种设计模式的应用实例_第13张图片

Facade设计模式

Facade模式不仅可以用来创建更简单的接口,还能用来减少客户必须处理的对象数量。下面分别从这两个方面介绍Facade模式的作用。

创建更简单的接口

LAME是一个开源的MP3音频压缩软件。由于其开源性,很多用户利用它将其它音频格式转变成MP3格式。其源码中定义了几十个上百个函数供开发者调用,但是对我们来说其中的绝大部分函数都用不到,因为我们仅仅打算把WAV格式的音频编码成MP3格式而已。然而,即使我们要完成的工作很简单,我们仍需要调用若干函数并把它们有机地配合起来才能顺利地将WAV格式转变成MP3格式。所以我们打算写一个接口函数来方便我们使用,我们将这个函数定义为

void convertAudio(string inputPath, string outputPath)

可以看到它只有两个参数,一个是输入音频文件的路径,另一个是输出音频文件的路径,非常简单易用。
这个函数的实现代码如下:

void convertAudio(string inputPath, string outputPath) {
    char* inputname = inputPath;
    char* outputname = outputPath;
    FILE * wav = fopen(inputname,"rb");
    FILE * mp3 = fopen(outputname,"wb");
    int read;
    int write;
    short int wav_buffer[8192*2];
    unsigned char mp3_buffer[8192];
    lame_t lame = lame_init();
    lame_set_in_samplerate(lame,44100);
    lame_set_num_channels(lame,2);
    lame_set_VBR(lame,vbr_default);
    lame_init_params(lame);
    int total=0;
    do {
        read = fread(wav_buffer,sizeof(short int)*2, 8192,wav);
        total += (read*4);
        if(read==0) {
            write = lame_encode_flush(lame,mp3_buffer,8192);
            fwrite(mp3_buffer,sizeof(char),write,mp3);
        } else {
            write = lame_encode_buffer_interleaved(lame,wav_buffer,read,mp3_buffer,8192);
            fwrite(mp3_buffer,sizeof(char),write,mp3);
        }
    }while(read!=0); 
    lame_close(lame);
    fclose(mp3);
    fclose(wav);
}

可以看到convertAudio给我们隐藏了复杂的底层实现,我们只需要与convertAudio函数打交道,而不用管复杂系统内部是怎么实现的。
各种设计模式的应用实例_第14张图片

减少必须处理的对象数量

代码:

package bupt.xujinliang.facadesample;

public class FacadeSample {
    public static void main(String[] args) {
        Customer customer = new Customer();
        customer.shopOnLine();
    }
}
class Customer {
    Tmall tmall;
    public Customer() {
        tmall = new Tmall();
    }
    public void shopOnLine() {
        tmall.doBusiness();
    }
}
class Tmall {
    Bank bank;
    Delivery delivery;
    Merchant merchant;
    public Tmall() {
        bank = new Bank();
        merchant = new Merchant();
        delivery = new Delivery();
    }
    public void doBusiness() {
        bank.getMoney();
        merchant.pay();
        delivery.pay();
    }
}
class Bank {
    public void getMoney() {
        System.out.println("Get money from Bank");
    }
}
class Merchant {
    public void pay() {
        System.out.println("Pay money to Merchant");
    }
}
class Delivery {
    public void pay(){
        System.out.println("Pay money to Delivery");
    }

}

UML图:
各种设计模式的应用实例_第15张图片

代码:

package bupt.xujinliang.facadesample;

public class FacadeSample {
    public static void main(String[] args) {
        Customer customer = new Customer();
        customer.shopOnLine();
    }
}
class Customer {
    Bank bank;
    Delivery delivery;
    Merchant merchant;
    public Customer() {
        bank = new Bank();
        merchant = new Merchant();
        delivery = new Delivery();
    }
    public void shopOnLine() {
        bank.getMoney();
        merchant.pay();
        delivery.pay();
    }
}
class Bank {
    public void getMoney() {
        System.out.println("Get money from Bank");
    }
}
class Merchant {
    public void pay() {
        System.out.println("Pay money to Merchant");
    }
}
class Delivery {
    public void pay(){
        System.out.println("Pay money to Delivery");
    }   
}

UML图:
各种设计模式的应用实例_第16张图片

Abstract Factory设计模式

代码:

package bupt.xujinliang.abstractfactory;

public class AbstractFactoryTest {
    public static void main(String[] args) {
        AbstractFactory lowFactory,highFactory;
        lowFactory = new LowFactory();
        highFactory = new HighFactory();
        lowFactory.getDisplay().print();
        lowFactory.getPrinter().print();
        highFactory.getDisplay().print();
        highFactory.getPrinter().print();       
    }
}
abstract class AbstractDisplay {
    abstract public void print();   
}
class LowDisplay extends AbstractDisplay {
    public void print() {   
        System.out.println("LowDisplay");
    }   
}
class HighDisplay extends AbstractDisplay {
    public void print() {
        System.out.println("HighDisplay");
    }   
}
abstract class AbstractPrinter {
    abstract public void print();
}
class LowPrinter extends AbstractPrinter {
    public void print() {
        System.out.println("LowPrinter");
    }   
}
class HighPrinter extends AbstractPrinter {
    public void print() {   
        System.out.println("HighDisplay");
    }   
}
abstract class AbstractFactory {
    AbstractDisplay display;
    AbstractPrinter printer;
    abstract public AbstractDisplay getDisplay();
    abstract public AbstractPrinter getPrinter();
}
class LowFactory extends AbstractFactory {
    public AbstractDisplay getDisplay() {
        display = new LowDisplay();
        return display;
    }
    public AbstractPrinter getPrinter() {
        printer = new LowPrinter();
        return printer;
    }   
}
class HighFactory extends AbstractFactory {
    public AbstractDisplay getDisplay() {
        display = new HighDisplay();
        return display;
    }
    public AbstractPrinter getPrinter() {
        printer = new HighPrinter();
        return printer;
    }   
}

UML图:
各种设计模式的应用实例_第17张图片

为什么称这个模式是Abstract Factory模式呢?初看起来,很容易认为这是因为工厂是用抽象类的派生类实现的。但事实并非如此。这个模式之所以成为Abstract Factory,是因为要创建的东西本身是由抽象类(上例是AbstractDisplay和AbstractPrinter)定义的。

Factory Method设计模式

代码:

package bupt.xujinliang.factorymethod;
/** * * @author jin * */
public class FactoryMethodTest {
    public static void main(String[] args) {          
        AbstractHumanFactory factory = new HumanFactory();           
        System.out.println("--造出一批白色人种--");  
        Human whiteHuman = factory.createHuman(WhiteHuman.class);
        whiteHuman.getColor();       
        whiteHuman.talk();           
        System.out.println("\n--造出一批黑色人种--");        
        Human blackHuman = factory.createHuman(BlackHuman.class);        
        blackHuman.getColor();       
        blackHuman.talk();           
        System.out.println("\n--造出一批黄色人种--");        
        Human yellowHuman = factory.createHuman(YellowHuman.class);      
        yellowHuman.getColor();      
        yellowHuman.talk();  
        }
}
interface Human {
    public void getColor();
    public void talk();
}
class BlackHuman implements Human {  
    public void getColor(){ 
        System.out.println("黑色人种的皮肤是黑色的!");
    } 
    public void talk() {
        System.out.println("黑人说话"); 
    } 
}
class YellowHuman implements Human {
    public void getColor(){ 
        System.out.println("黄色人种的皮肤是黄色的!");
    } 
    public void talk() { 
        System.out.println("黄色人种说话"); 
    } 
}
class WhiteHuman implements Human { 
    public void getColor(){ 
        System.out.println("白色人种的皮肤是白色的!"); 
    } 
    public void talk() {
        System.out.println("白色人种说话"); 
    }
}
abstract class AbstractHumanFactory {    
    public abstract Human createHuman(Class<? extends Human> c);
}
class HumanFactory extends AbstractHumanFactory {
    Human human;
    public Human createHuman(Class<? extends Human> c){ 
        try { 
            human =  (Human)Class.forName(c.getName()).newInstance(); 
        } catch (Exception e) {
            System.out.println("生成错误!"); 
        }
        return human;
    }
}

UML图:
各种设计模式的应用实例_第18张图片

Strategy设计模式

代码:

package bupt.xujinliang.strategy;
/** * * @author jin * */
public class Strategy {
    public static void main(String[] args) {
        PersonContext person = new PersonContext(new TrainStrategy());
        person.travel();
        person.setTravelStrategy(new BicycleStrategy());
        person.travel();
        person.setTravelStrategy(new AirPlanelStrategy());
        person.travel();
    }
}
interface TravelStrategy {
    abstract public void travelAlgorithm();
}
class AirPlanelStrategy implements TravelStrategy {  
    public void travelAlgorithm(){  
        System.out.println("travel by AirPlain");  
    }  
} 
class TrainStrategy implements TravelStrategy {  
    public void travelAlgorithm(){  
        System.out.println("travel by Train");  
    }  
} 
class BicycleStrategy implements TravelStrategy {  
    public void travelAlgorithm(){  
        System.out.println("travel by Bicycle");  
    }  
} 
class PersonContext {
    private TravelStrategy travelStrategy;
    public PersonContext(TravelStrategy travelStrategy) {
        this.travelStrategy = travelStrategy;
    }
    public void setTravelStrategy(TravelStrategy travelStrategy) {
        this.travelStrategy = travelStrategy;
    }
    public void travel() {
        this.travelStrategy.travelAlgorithm();
    }
}

UML图:
各种设计模式的应用实例_第19张图片

Template Method设计模式

代码:

package bupt.xujinliang.templatemethod;
/** * * @author jin * */
public class TemplateMethod {
    public static void main(String[] args) {  
        Tea tea = new Tea();  
        Coffee coffee = new Coffee();  
        tea.prepareSteps();  
        coffee.prepareSteps();  
    } 
}
abstract class Beverage {
    public final void prepareSteps() { 
        System.out.println("**************************************");
        boilWater(); //把水煮沸 
        brew();  //调制 
        pourInCup(); //把饮料倒进杯子 
        addCondiments(); //添加作料 
    }  
    protected abstract void brew();  
    protected abstract void addCondiments();  
    protected void boilWater() {  
        System.out.println("把水煮沸");  
    }  
    protected void pourInCup() {  
        System.out.println("倒入杯子");  
    }  
} 
class Coffee extends Beverage {        
    protected void addCondiments() {  
        System.out.println("添加糖和牛奶");  
    }   
    protected void brew() {  
        System.out.println("过滤咖啡");  
    }   
} 
class Tea extends Beverage {   
    protected void addCondiments() {  
        System.out.println("加柠檬");  
    }  
    protected void brew() {  
        System.out.println("浸泡茶叶");  
    }  
}

UML图:
各种设计模式的应用实例_第20张图片

Object Pool设计模式

代码1:

package bupt.xujinliang.objectpool2;

/** * @jin */
import java.sql.Connection; 
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Vector;

public class ObjectPoolTest {
    public static void main(String[] args) {
        JDBCConnectionPool dbConnPool;
        dbConnPool= new JDBCConnectionPool("com.mysql.jdbc.Driver",
                "jdbc:mysql://127.0.0.1:3306/test","root","");//
        Connection conn1 = dbConnPool.getObj();
        dbConnPool.passObj(conn1);
        Connection conn2 = dbConnPool.getObj();
        Connection conn3 = dbConnPool.getObj();
        Connection conn4 = dbConnPool.getObj();
        Connection conn5 = dbConnPool.getObj();
        dbConnPool.passObj(conn2);
        dbConnPool.passObj(conn3);
        dbConnPool.passObj(conn4);
        dbConnPool.passObj(conn5);
    } 
}
class JDBCConnectionPool {
    private Vector<Connection> locked, unlocked; 
    static int poolCapacity = 3;
    private String url, usr, pwd; 
    public JDBCConnectionPool(String driver, String url, String usr,
            String pwd) {
        locked = new Vector<Connection>();
        unlocked = new Vector<Connection>();
        try {
            Class.forName(driver).newInstance();
        } catch(Exception e) {
            e.printStackTrace();
        }
        this.url = url;
        this.usr = usr;
        this.pwd = pwd;
    }
    public synchronized Connection getObj() {
        Connection t;
        if (unlocked.size() > 0) {
            Iterator<Connection> iter = unlocked.iterator();
            while(iter.hasNext()) {
                t = iter.next();
                if(isValid(t)) {   
                    System.out.println("取出对象");
                    unlocked.remove(t);
                    locked.add(t);
                    return t;
                } else {   
                    unlocked.remove(t);
                    expire(t);
                }
            }
        }
        if(poolCapacity > locked.size()+unlocked.size()) {
            t = create();
            locked.add(t);
            return t;   
        } else {
            System.out.println("对象池已满,返回无效对象");
            return null;
        }
    } 
    public synchronized void passObj(Connection t) {
        locked.remove(t);
        if(null == t) {
            System.out.println("无效对象,无需放回");
        } else if(isValid(t)) {   
            System.out.println("放回对象");
            unlocked.add(t);
        } else {   
            expire(t);
        }
    }
    protected Connection create() {
        try {
            System.out.println("新建对象");
            return DriverManager.getConnection(url, usr, pwd);
        } catch(SQLException e) {
            e.printStackTrace();
        }
        return null;
    } 
    protected boolean isValid(Connection o) {
        try {
            return !o.isClosed();
        } catch(SQLException e) {
            e.printStackTrace();
        }
        return false;
    } 
    protected void expire(Connection o) {
        try {
            o.close();
        } catch(SQLException e) {
            e.printStackTrace();
        } finally {
            o = null;
        }
    }
 }

UML图:
各种设计模式的应用实例_第21张图片

运行截图:
各种设计模式的应用实例_第22张图片

代码2:

package bupt.xujinliang.objectpool2;

/** * @jin */
import java.sql.Connection; 
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Vector;

public class ObjectPoolTest {
    public static void main(String[] args) {
        JDBCConnectionPool dbConnPool;
        dbConnPool= new JDBCConnectionPool("com.mysql.jdbc.Driver",
                "jdbc:mysql://127.0.0.1:3306/test","root","");//
        Connection conn1 = dbConnPool.getObj();
        dbConnPool.passObj(conn1);
        Connection conn2 = dbConnPool.getObj();
        Connection conn3 = dbConnPool.getObj();
        Connection conn4 = dbConnPool.getObj();
        Connection conn5 = dbConnPool.getObj();
        dbConnPool.passObj(conn2);
        dbConnPool.passObj(conn3);
        dbConnPool.passObj(conn4);
        dbConnPool.passObj(conn5);
    } 
}
class JDBCConnectionPool {
    private Vector<Connection> locked, unlocked; 
    static int poolCapacity = 3;
    private String url, usr, pwd; 
    public JDBCConnectionPool(String driver, String url, String usr,
            String pwd) {
        locked = new Vector<Connection>();
        unlocked = new Vector<Connection>();
        try {
            Class.forName(driver).newInstance();
        } catch(Exception e) {
            e.printStackTrace();
        }
        this.url = url;
        this.usr = usr;
        this.pwd = pwd;
    }
    public synchronized Connection getObj() {
        Connection t;
        int num;
        if (unlocked.size() > 0) {
            Iterator<Connection> iter = unlocked.iterator();
            while(iter.hasNext()) {
                t = iter.next();
                if(isValid(t)) {   
                    System.out.println("取出对象");
                    unlocked.remove(t);
                    locked.add(t);
                    return t;
                } else {   
                    unlocked.remove(t);
                    expire(t);
                }
            }
        }
        num = locked.size()+unlocked.size();
        if(poolCapacity > num) {
            t = create();
            locked.add(t);
            System.out.println("新建对象,此时对象数目:"+(num+1));
            return t;   
        } else {
            System.out.println("对象池已满,返回无效对象,已有对象数目:"+num);
            return null;
        }
    } 
    public synchronized void passObj(Connection t) {
        locked.remove(t);
        if(null == t) {
            System.out.println("无效对象,无需放回");
        } else if(isValid(t)) { 
            unlocked.add(t);
            System.out.println("放回对象");
        } else {   
            expire(t);
        }
    }
    protected Connection create() {
        try {       
            System.out.println("新建对象");
            return DriverManager.getConnection(url, usr, pwd);      
        } catch(SQLException e) {
            e.printStackTrace();
        }
        return null;
    } 
    protected boolean isValid(Connection o) {
        try {
            return !o.isClosed();
        } catch(SQLException e) {
            e.printStackTrace();
        }
        return false;
    } 
    protected void expire(Connection o) {
        try {
            o.close();
        } catch(SQLException e) {
            e.printStackTrace();
        } finally {
            o = null;
        }
    }
 }

UML图:
各种设计模式的应用实例_第23张图片

运行结果:
各种设计模式的应用实例_第24张图片

Iterator设计模式

代码:

package bupt.xujinliang.iterator;
/** * @jin */
import java.util.ArrayList;
public class IteratorPattern {
    public static void main(String[] args) {
        ConcreteAggregate<String> aggregate=new ConcreteAggregate<String>();
        aggregate.add("A");
        aggregate.add("B");
        aggregate.add("C");
        aggregate.add("D");
        aggregate.add("E");
        Iterator iterator=aggregate.createIterator();
            for(iterator.first();!iterator.isDone();iterator.next()){
            System.out.println(iterator.currentItem());
        }
    }
}
interface Iterator<E> {
    public void first();
    public void next();
    public E currentItem();
    public boolean isDone();
}
abstract class Aggregate<E> {
    protected abstract Iterator createIterator();
}
class ConcreteAggregate<E> extends Aggregate<E> {
    private ArrayList<E> arrayList=new ArrayList<E>();
    public Iterator createIterator() {
        return new ConcreteIterator<E>(this);
    }
    public void add(E o){
        arrayList.add(o);
    }
    public E getElement(int index) {
        if (index<arrayList.size()) {
            return arrayList.get(index);
        } else {
            return null;
        }
    }
    public int getSize(){
        return arrayList.size();
    }
}
class ConcreteIterator<E> implements Iterator<E> {
    private ConcreteAggregate<E> agg;
    private int index=0;
    private int size=0;
    public ConcreteIterator( ConcreteAggregate<E> aggregate) {
        this.agg=aggregate;
        this.index=0;
        this.size=aggregate.getSize();
    }
    public E currentItem() {
        return agg.getElement(index);
    }
    public void first() {
        index=0;
    }
    public boolean isDone() {
        if(index>=size){
            return true;
        }
        return false;
    }
    public void next() {
        if(index<size){
            index++; 
        }
    }
}

UML图:
各种设计模式的应用实例_第25张图片

你可能感兴趣的:(各种设计模式的应用实例)