设计模式

设计模式

 
 

创建模式

工厂模式

总共有四个角色:

  • 工厂类角色:是具体产品类角色直接调用者。
  • 抽象产品角色:接口或抽象类,负责具体产品角色的定义,及与客户端的交互。
  • 具体产品角色:被工厂类创建的对象,也是客户端实际操作对象。
  • 客户端:调用工厂类产生实例,并调用实例的方法进行相应工作。

    1. 简单工厂
      Alt text
      • 使用的情景:在具体不是到需要实例化哪一种类的类型,而且类型数量有限,可以考虑使用简单工厂。
      • 代码示例:
public Interface Product{
    public void function();
}
public class ProductA implements Product{
    public void function(){//具体实现接口功能
}
}
public class ProductB implements Product{
    public void function(){//具体实现接口功能
    }
}
public class ProductCreator{
    public Product createProduct(String type){
        if('a'.equals(type))
            return new ProductA();
        else if('a'.equals(type))
            return new ProductA();
        }
        else
            return null;
        }
  1. 抽象工厂
    类图:Alt text
    例子:Alt text
public Interface Factory{
    public Car createCar();
}

public BMWFactory implements Factory{
    public Car createCar(){
        //......
        return aCar;
    }
}

public BuickFactory implements Factory{
    public Car createCar(){
        //......
        return aCar;
    }
}

public interface Car{
    public void carService();
}

public Buick implements Car{
    public void carService(){
    }
}

public BMW implements Car{
    public void carService(){
    }
}

public class Client{
    public Static void main(String[] args){
        Factory fac = new BMWFactory();
        Car mycar = fac.createCar();
        mycar.carService();
    }
}

原型模式

用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。
Alt text
原型类必须具备两个条件:实现Cloneable接口、重载Object的clone函数
应用场景(或优势):

  1. 使用原型模式的性能比new的性能好,特别是创建含有复杂数据对象的类时;
  2. 简化对象创建过程

    注意点:在实际重载Object的复制的过程中,如果简单的只是拷贝了对象,那么,对象中的基础类型和String类型是深度拷贝的,但是其他容器或复杂类型是浅拷贝的,需要手动进行深拷贝。


例子:
class Prototype implements Cloneable {
    public Prototype clone(){
        Prototype prototype = null;
        try{
            prototype = (Prototype)super.clone();
        }catch(CloneNotSupportedException e){
            e.printStackTrace();
        }
        return prototype; 
    }
}

class ConcretePrototype extends Prototype{
    public void show(){
        System.out.println("原型模式实现类");
    }
}

public class Client {
    public static void main(String[] args){
        ConcretePrototype cp = new ConcretePrototype();
        for(int i=0; i< 10; i++){
            ConcretePrototype clonecp = (ConcretePrototype)cp.clone();
            clonecp.show();
        }
    }
}

单例模式

确保一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。 ![Alt text](./单例模式.png) 单例模式根据实例化对象时机的不同分为两种:一种是饿汉式单例,一种是懒汉式单例。饿汉式单例在单例类被加载时候,就实例化一个对象交给自己的引用;而懒汉式在调用取得实例方法的时候才会实例化对象。
  1. 饿汉式

    public class Singleton {
        private static Singleton singleton = new Singleton();
        private Singleton(){}
        public static Singleton getInstance(){
            return singleton;
        }
    }
  2. 懒汉式

    public class Singleton {
        private static Singleton singleton;
        private Singleton(){}
    
        public static synchronized Singleton getInstance(){
            if(singleton==null){
                singleton = new Singleton();
            }
            return singleton;
        }
    }

    应用场景(或优势)

    • 在内存中只有一个对象,节省内存空间。
    • 避免频繁的创建销毁对象,可以提高性能。
    • 避免对共享资源的多重占用。
    • 可以全局访问。

     

    当创建具有状态的工具类时;或频繁的读写某一文档;创建对象消耗过多资源,但是经常用到


结构模式

门面模式

代理模式

适配器模式

组合模式

装饰者模式

桥梁模式

享元模式


行为模式

模板模式

备忘录模式

观察者模式

Alt text
Alt text

  1. 推(所有观察者获得相同的数据)
    Alt text
    主题:
public class WeacherData extends Observable {  

    private int data1;  

    private int data2;  


    public void update(){  
        this.setChanged();  
        //这里将WeacherData 对象传递给观察者属于推模式  
             this.notifyObservers(this);  
    }  

    public int getData1() {  
        return data1;  
    }  

    public int getData2() {  
        return data2;  
    }  

    public void setData(int data1,int data2){  
        this.data1 = data1;  
        this.data2 = data2;  
    }  

}  

观察者:

public class ClientData implements Observer {
    Observable obser;
    private int data1;

    private int data2;


    public  ClientData(Observable obser){
        this.obser = obser;
        obser.addObserver(this);

    }

    @Override
    public void update(Observable o, Object arg) {
        // TODO Auto-generated method stub
        if(o instanceof WeacherData ){
            WeacherData w = (WeacherData)arg;
            //data = w.getData1();
            data1 = w.getData1();
            data2 = w.getData2();
            display();
        }

    }

    public void display(){
        System.out.println("data1 is "+data1+" and data2 is "+data2);
    }

}
  1. 拉(观察者获取自己关心的数据)
    Alt text
    主题:
import java.util.Observable;
import java.util.Observer;

public class WeatherData extends Observable {
    private float temperature;
    private float humidity;
    private float pressure;

    public WeatherData() { }
    public void measurementsChanged() {
        setChanged();
        notifyObservers();
    }
    public void setMeasurements(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }
    public float getTemperature() {
        return temperature;
    }
    public float getHumidity() {
        return humidity;
    }
    public float getPressure() {
        return pressure;
    }
}

观察者:

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

public class CurrentConditionsDisplay implements Observer, DisplayElement {
    Observable observable;
    private float temperature;
    private float humidity;

    public CurrentConditionsDisplay(Observable observable) {
        this.observable = observable;
        observable.addObserver(this);
    }

    public void update(Observable obs, Object arg) {
        if (obs instanceof WeatherData) {
            WeatherData weatherData = (WeatherData) obs;
            this.temperature = weatherData.getTemperature();
            this.humidity = weatherData.getHumidity();
            display();
        }
    }

    public void display() {
        System.out.println("Current conditions: " + temperature
                + "F degrees and " + humidity + "% humidity");
    }
}

责任链模式

命令模式

状态模式

策略模式

中介模式

解释器模式

访问者模式

 

turn temperature; } public float getHumidity() { return humidity; } public float getPressure() { return pressure; } }

观察者:

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

public class CurrentConditionsDisplay implements Observer, DisplayElement {
    Observable observable;
    private float temperature;
    private float humidity;

    public CurrentConditionsDisplay(Observable observable) {
        this.observable = observable;
        observable.addObserver(this);
    }

    public void update(Observable obs, Object arg) {
        if (obs instanceof WeatherData) {
            WeatherData weatherData = (WeatherData) obs;
            this.temperature = weatherData.getTemperature();
            this.humidity = weatherData.getHumidity();
            display();
        }
    }

    public void display() {
        System.out.println("Current conditions: " + temperature
                + "F degrees and " + humidity + "% humidity");
    }
}

责任链模式

命令模式

状态模式

策略模式

中介模式

解释器模式

访问者模式

 
posted @ 2015-04-14 09:38  hgfdodo  阅读(409)  评论(0)    收藏  举报