`

责任型模式

 
阅读更多
Singleton(单例)模式
最简单的单例
public class Singleton {
    private static Singleton instance = new Singleton();
    //other useful fields...

    private Singleton() {
    }

    public static Singleton getInstance() {
        return instance;
    }

    //other useful methods...
}

延迟创建
public class UnThreadSafeSingelton {
    private static UnThreadSafeSingelton instatnce;

    private UnThreadSafeSingelton() {
    }

    public static UnThreadSafeSingelton getInstance() {
        if (instatnce == null) {
            instatnce = new UnThreadSafeSingelton();
        }
        return instatnce;
    }
}

线程安全
public class ThreadSafeSingelton {
    private static ThreadSafeSingelton instatnce;

    private ThreadSafeSingelton() {
    }

    public static synchronized ThreadSafeSingelton getInstance() {
        if (instatnce == null) {
            instatnce = new ThreadSafeSingelton();
        }
        return instatnce;
    }
}


Double-Check Locking
public class DoubleCheckSingleton {
    private volatile static DoubleCheckSingleton instatnce = null;

    private DoubleCheckSingleton() {
    }

    public static DoubleCheckSingleton getInstance() {
        if (instatnce == null) { //  check if it is created.
            synchronized (DoubleCheckSingleton.class) {//synchronize creation block
                if (instatnce == null) //double check if it is created
                    instatnce = new DoubleCheckSingleton();
            }
        }
        return instatnce;
    }
}

Initialization on demand holder
public class LazyLoadedSingleton {
    private LazyLoadedSingleton() {
    }

    private static class LazyHolder {  //holds the singleton class
        private static final LazyLoadedSingleton singletonInstatnce = new LazyLoadedSingleton();
    }

    public static LazyLoadedSingleton getInstance() {
        return LazyHolder.singletonInstatnce;
    }
}

Singleton的序列化
import java.io.Serializable;
public class SerialibleSingleton implements Serializable {
    private static final long serialVersionUID = -6099617126325157499L;
    static SerialibleSingleton singleton = new SerialibleSingleton();

    private SerialibleSingleton() {
    }

    public static SerialibleSingleton getInstance() {
        return singleton;
    }

    // This method is called immediately after an object of this class is deserialized.
    // This method returns the singleton instance.

    private Object readResolve() {
        return singleton;
    }
}

测试
public class Client {
    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance();
        UnThreadSafeSingelton unThreadSafeSingelton = UnThreadSafeSingelton.getInstance();
        ThreadSafeSingelton threadSafeSingelton = ThreadSafeSingelton.getInstance();
        DoubleCheckSingleton doubleCheckSingleton = DoubleCheckSingleton.getInstance();
        LazyLoadedSingleton lazyLoadedSingleton = LazyLoadedSingleton.getInstance();
        SerialibleSingleton serialibleSingleton = SerialibleSingleton.getInstance();
    }
}

Observer(观察者)模式
普通观察者模式
package com.test;
public interface StockBuyer {
    void update(float price);
}
package com.test;
public class PrivateInvestor implements StockBuyer {
    private String name;
    private float maxPrice;
    private float minPrice;

    public PrivateInvestor(String name, float maxPrice, float minPrice, Stock stock) {
        this.name = name;
        this.maxPrice = maxPrice;
        this.minPrice = minPrice;
        stock.addBuyers(this);
    }

    @Override
    public void update(float price) {
        if (price > maxPrice) {
            System.out.printf("%s is buying 500 shares...\n", name);
        }

        if (price < minPrice) {
            System.out.printf("%s is selling 1000 stocks...\n", name);
        }
    }
}
package com.test;
public class InstitutionalInvestor implements StockBuyer {
    private String name;
    private float maxPrice;
    private float minPrice;

    public InstitutionalInvestor(String name, float maxPrice, float minPrice, Stock stock) {
        this.name = name;
        this.maxPrice = maxPrice;
        this.minPrice = minPrice;
        stock.addBuyers(this);
    }

    @Override
    public void update(float price) {
        if (price > maxPrice) {
            System.out.printf("%s is selling 100000 stocks...\n", name);
        }

        if (price < minPrice) {
            System.out.printf("%s is buying 20000 shares...\n", name);
        }
    }
}
package com.test;
import java.util.LinkedList;
import java.util.List;
import static java.lang.Math.abs;
public class Stock {
    private static final float maxGainAndLoss=0.05f;//5%
    private float price;
    private List<StockBuyer> buyers;

    public Stock(float price) {
        this.price = price;
        buyers = new LinkedList<StockBuyer>();
    }

    public void addBuyers(StockBuyer buyer) {
        if (buyer != null) buyers.add(buyer);
    }

    public void removeBuyers(StockBuyer buyer) {
        if (buyer != null) buyers.remove(buyer);
    }

    public void notifyBuyer() {
        for (StockBuyer buyer : buyers) {
            buyer.update(price);
        }
    }

    public void setPrice(float newPrice) {
        if (newPrice < 0) {
            throw new IllegalArgumentException("Price can not be negative!");
        }

        //update price and calculate change...
        float oldPrice = price;
        price = newPrice;
        float gainAndLoss = (newPrice - oldPrice) / oldPrice;//calculate change
        System.out.printf("Previous price: %g. Current price: %g. Loss/Gain: %g%%.\n", oldPrice, newPrice, gainAndLoss*100);

        //if change beyond maxGainAndLoss, notify stock buyers
        if (abs(gainAndLoss) > maxGainAndLoss) {
            notifyBuyer();
        }
    }
}
package com.test;
public class TestDrive {
    public static void main(String[] args) {
        Stock stock = new Stock(19f);
        InstitutionalInvestor institutionalInvestor = new InstitutionalInvestor("Company E", 20f, 18.5f, stock);
        PrivateInvestor privateInvestor = new PrivateInvestor("Xiao D", 20f, 18.9f, stock);

        stock.setPrice(19.0224f);
        System.out.println();

        stock.setPrice(20.923f);
        System.out.println();

        stock.setPrice(18.8938f);
        System.out.println();

        stock.setPrice(19.9938f);
    }
}

Java标准库的观察者模式
import java.util.Observable;
import java.util.Observer;
public class InstitutionalInvestor implements Observer {
    private String name;
    private float maxPrice;
    private float minPrice;

    public InstitutionalInvestor(String name, float maxPrice, float minPrice, Stock stock) {
        this.name = name;
        this.maxPrice = maxPrice;
        this.minPrice = minPrice;
        stock.addObserver(this);
    }

    @Override
    public void update(Observable o, Object arg) {
        float price = (Float) arg;
        if (price > maxPrice) {
            System.out.printf("%s is selling 100000 stocks...\n", name);
        }

        if (price < minPrice) {
            System.out.printf("%s is buying 20000 shares...\n", name);
        }
    }
}
import java.util.Observable;
import java.util.Observer;
public class PrivateInvestor implements Observer {
    private String name;
    private float maxPrice;
    private float minPrice;

    public PrivateInvestor(String name, float maxPrice, float minPrice, Stock stock) {
        this.name = name;
        this.maxPrice = maxPrice;
        this.minPrice = minPrice;
        stock.addObserver(this);
    }

    @Override
    public void update(Observable o, Object arg) {
        float price = (Float) arg;
        if (price > maxPrice) {
            System.out.printf("%s is buying 500 shares...\n", name);
        }

        if (price < minPrice) {
            System.out.printf("%s is selling 1000 stocks...\n", name);
        }
    }
}
import java.util.Observable;
import static java.lang.Math.abs;
public class Stock extends Observable {
    private static final float maxGainAndLoss=0.05f;//5%
    private float price;

    public Stock(float price) {
        super();
        this.price = price;
    }

    public void setPrice(float newPrice) {
        if (newPrice < 0) {
            throw new IllegalArgumentException("Price can not be negative!");
        }

        //update price and calculate change...
        float oldPrice = price;
        price = newPrice;
        float gainAndLoss = (newPrice - oldPrice) / oldPrice;//calculate change
        System.out.printf("Previous price: %g. Current price: %g. Loss/Gain: %g%%.\n", oldPrice, newPrice, gainAndLoss*100);

        //if change beyond maxGainAndLoss, notify stock buyers
        if (abs(gainAndLoss) > maxGainAndLoss) {
            setChanged();
            notifyObservers(price);
        }
    }
}


Mediator(中介者)模式

Proxy(代理)模式
静态代理

public interface Service {
    String hello();
}
public class ServiceImpl implements Service {
    @Override
    public String hello() {
        return "Server says hello!";
    }
}
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
public class Service_Skeleton extends Thread {
    private Service service;

    public Service_Skeleton(Service service) {
        this.service = service;
    }

    @Override
    public void run() {
        ServerSocketChannel serverSocketChannel = null;
        Selector sel = null;
        SocketChannel ch = null;
        boolean finished=false;
        try {
            ByteBuffer buffer = ByteBuffer.allocate(32);
            serverSocketChannel = ServerSocketChannel.open();
            sel = Selector.open();

            serverSocketChannel.socket().bind(new InetSocketAddress(InetAddress.getLocalHost(), 3900));
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.register(sel, SelectionKey.OP_ACCEPT);

            String encoding = System.getProperty("file.encoding");
            Charset cs = Charset.forName(encoding);

            while (!finished) {
                sel.select();
                Iterator it = sel.selectedKeys().iterator();
                while (it.hasNext()) {
                    SelectionKey skey = (SelectionKey) it.next();
                    it.remove();
                    if (skey.isAcceptable()) {//select a channel to read and write
                        ch = serverSocketChannel.accept();
                        ch.configureBlocking(false);
                        //register a read operatioin
                        ch.register(sel, SelectionKey.OP_READ);
                    } else if (skey.isReadable()) {
                        ch = (SocketChannel) skey.channel();
                        //read info from this channel
                        if (ch.read((ByteBuffer) buffer.clear()) > 0) {
                            buffer.flip();
                            String method = cs.decode(buffer).toString();
                            //if it says "hello", register a write operation
                            if ("hello".equals(method)) {
                                ch.register(sel, SelectionKey.OP_WRITE);
                            }
                        }
                    } else { // is writable
                        ch = (SocketChannel) skey.channel();
                        // invoke the service.hello method and write the result into the channel
                        ch.write(ByteBuffer.wrap(service.hello().getBytes()));
                        ch.close();//close the channel
                        finished=true;//quit server
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ch != null) ch.close();
                if (serverSocketChannel != null) serverSocketChannel.close();
                if (sel != null) sel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Service_Skeleton Service_Skeleton = new Service_Skeleton(new ServiceImpl());
        Service_Skeleton.start();
    }
}
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
public class Service_Stub implements Service {

    @Override
    public String hello() {
        SocketChannel socketChannel = null;
        Selector sel = null;
        try {
            socketChannel = SocketChannel.open();
            InetSocketAddress inetSocketAddress = new InetSocketAddress(InetAddress.getLocalHost(), 3900);

            sel = Selector.open();
            socketChannel.connect(inetSocketAddress);
            socketChannel.configureBlocking(false);
            socketChannel.register(sel, SelectionKey.OP_WRITE);
            ByteBuffer byteBuffer = ByteBuffer.allocate(32);

            String encoding = System.getProperty("file.encoding");
            Charset cs = Charset.forName(encoding);
            while (true) {
                sel.select();
                Iterator it = sel.selectedKeys().iterator();
                while (it.hasNext()) {
                    SelectionKey key = (SelectionKey) it.next();
                    it.remove();
                    if (key.isReadable()) {//read the result of remote service's method hello
                        if (socketChannel.read((ByteBuffer) byteBuffer.clear()) > 0) {//read the result
                            byteBuffer.flip();
                            socketChannel.close();//close the channel and return
                            return cs.decode(byteBuffer).toString();//return result
                        }
                    } else {  //is writable, request remote service's hello method
                        //write "hello" to skeleton...
                        socketChannel.write(ByteBuffer.wrap("hello".getBytes()));
                        //register a read operatioin to wait for the response...
                        socketChannel.register(sel, SelectionKey.OP_READ);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socketChannel != null) socketChannel.close();
                if (sel != null) sel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
public class Client {
    public static void main(String[] args) {
        Service service = new Service_Stub();
        String result = service.hello();
        System.out.println(result);
    }
}

动态代理
参考http://blgaici1.iteye.com/admin/blogs/1048164

Chain of Reponsibility(责任链)模式

Flyweight(享员)模式
  • 大小: 22.8 KB
分享到:
评论

相关推荐

    c++设计模式-行为型模式-责任链模式

    c++设计模式-行为型模式-责任链模式;qt工程;c++简单源码; 责任链(Chain of Responsibility)模式的定义:为了避免请求发送者与多个请求处理者耦合在一起,于是将所有请求的处理者通过前一对象记住其下一个对象的...

    JAVA-设计模式-行为型模式-责任链模式

    JAVA-设计模式-行为型模式-责任链模式

    责任链模式例子

    在《Head First Design Patterns》文中是这么介绍责任链模式的,“通过责任链模式,你可以为某个请求创建一个对象链。每个对象依次检查此请求,并对其进行处理,或者将它传给链中的下一个...责任链模式属于行为型模式。

    设计模式_行为型_责任链模式.md

    设计模式_行为型_责任链模式

    设计模式-C++

    创建型模式,共五种:工厂方法模式、抽象工厂模式、...行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。

    23种设计模式项目实例

    创建型模式,共五种:工厂方法模式、抽象工厂模式、...行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。

    java常用23中设计模式

    行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。 其实还有两类:并发型模式和线程池模式。

    23种JAVA设计模式和15种J2EE设计模式

    行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。 其实还有两类:并发型模式和线程池模式。

    c++设计模式-行为型模式-策略模式

    c++设计模式-行为型模式-策略模式;qt工程;c++简单源码; 策略(Strategy)模式的定义:该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。策略模式属于...

    java设计模式示例

    java设计模式示例 创建型模式(5种):工厂方法模式,...行为型模式(11种):策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。

    Java23种设计模式可直接运行Demo

    行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。 其实还有两类:并发型模式和线程池模式。

    23种设计模式实例

    总体来说设计模式分为三大类: ...行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式例子

    设计模式的精简版

    java设计模式的精简版,创建型模式:工厂方法模式,抽象...行为型模式:策略模式,模板方法模式,观察者模式,迭代子模式,责任链模式,命令模式,备忘录模式,状态模式,访问者模式,中介者模式,解释器模式,共11种

    23种设计模式java源码

    行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。 其实还有两类:并发型模式和线程池模式。

    设计模式自己总结一句话描述

    行为型模式,共十一种: 策略模式、模板方法模式、观察者模式、迭代器模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。 其实还有两类:并发型模式和线程池模式。

    23种设计模式 -设计模式图解.7z

    23种设计模式的特点定义、优缺点、使用场景,源码中...行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。

    23个设计模式完整DEMO

    C#版的23个设计模式完整DEMO,包括: ...行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。

    23种设计模式demo

    java的设计模式大体上分为三大类: ...行为型模式(11种):策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。

Global site tag (gtag.js) - Google Analytics