- 浏览: 140640 次
- 性别:
- 来自: 北京
-
文章分类
Singleton(单例)模式
最简单的单例
延迟创建
线程安全
Double-Check Locking
Initialization on demand holder
Singleton的序列化
测试
Observer(观察者)模式
普通观察者模式
Java标准库的观察者模式
Mediator(中介者)模式
Proxy(代理)模式
静态代理
动态代理
参考http://blgaici1.iteye.com/admin/blogs/1048164
Chain of Reponsibility(责任链)模式
Flyweight(享员)模式
最简单的单例
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(享员)模式
发表评论
-
设计模式理解
2012-02-24 11:07 01、SRP(Single Responsblity Princ ... -
扩展型模式
2011-09-01 11:28 787Decorator(装饰器)模式 意图是在运行时组合操作的新变 ... -
操作型模式
2011-08-31 10:05 623Template Method(模板)模式 State(状态 ... -
构造型模式
2011-08-29 20:12 855Builder(生成器)模式 Factory Method( ... -
接口型模式
2011-08-27 11:57 9511.Adapter(适配器)模式 对象适 配器(Object ...
相关推荐
- **责任型模式**:如单例模式、观察者模式、中介者模式、代理模式和职责链模式,这些模式主要处理对象间的职责分配和通信。 - **构造型模式**:包括生成器模式、工厂方法模式、抽象工厂模式,它们主要用于对象的...
c++设计模式-行为型模式-责任链模式;qt工程;c++简单源码; 责任链(Chain of Responsibility)模式的定义:为了避免请求发送者与多个请求处理者耦合在一起,于是将所有请求的处理者通过前一对象记住其下一个对象的...
4. **责任链模式**:责任链模式是行为型设计模式,它使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合。在这个模式中,请求沿着处理者链进行传递,每个处理者都有机会处理请求,或者将请求传递...
JAVA-设计模式-行为型模式-责任链模式
设计模式分为三大类:创建型模式、结构型模式和行为型模式。 **创建型模式**关注的是对象的创建。共有五种创建型模式: 1. **工厂方法模式**:它定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法...
在《Head First Design Patterns》文中是这么介绍责任链模式的,“通过责任链模式,你可以为某个请求创建一个对象链。每个对象依次检查此请求,并对其进行处理,或者将它传给链中的下一个...责任链模式属于行为型模式。
创建型模式(5): 工厂方法模式 、抽象工厂模式、单例模式、建造者模式、原型模式。 结构型模式(7): 适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。 行为型模式(11): 策略模式...
行为型设计模式中的一种——责任链模式,它提供了一种优雅的方式来处理对象间的通信,尤其是当多个对象都可能处理一个请求,且具体处理的哪个对象在运行时才能决定时。本文将详细介绍责任链模式的定义、角色组成、...
创建型模式,共五种:工厂方法模式、抽象工厂模式、...行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。
责任链模式是一种行为设计模式,它允许我们把请求沿着处理者链进行传递,直到某个处理者处理这个请求。这种模式让请求的发送者和接收者解耦,因为发送者无需知道哪个对象会处理请求,而接收者也无需知道请求来自哪里...
创建型模式,共五种:工厂方法模式、抽象工厂模式、...行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。
行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。 其实还有两类:并发型模式和线程池模式。
按照不同的功能特性,设计模式可以分为三大类:创建型模式、结构型模式和行为型模式。 #### 二、创建型模式 创建型模式主要用于解决对象创建的过程,旨在简化对象创建的复杂度,同时保持对象创建的灵活性。主要...
其中,行为型模式主要着眼于对象间的交互,以及如何有效地分配和管理职责,使软件设计更加灵活、易于扩展和维护。本文将详细介绍行为型设计模式,并深入分析两种典型的行为模式:职责链模式和命令模式。 首先,让...
责任链模式是软件设计模式中的一种行为模式,它允许在对象之间传递请求,同时让接收者决定是否处理这个请求。这种模式将请求的发送者和接收者解耦,使得多个对象都有机会处理一个请求,而无需显式指定具体的处理者。...
c++设计模式-行为型模式-策略模式;qt工程;c++简单源码; 策略(Strategy)模式的定义:该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。策略模式属于...
java设计模式示例 创建型模式(5种):工厂方法模式,...行为型模式(11种):策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。
行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。 其实还有两类:并发型模式和线程池模式。
总体来说设计模式分为三大类: ...行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式例子