责任型模式

[b]Singleton(单例)模式[/b]
[i]最简单的单例[/i]

public class Singleton {
private static Singleton instance = new Singleton();
//other useful fields...

private Singleton() {
}

public static Singleton getInstance() {
return instance;
}

//other useful methods...
}

[i]延迟创建[/i]

public class UnThreadSafeSingelton {
private static UnThreadSafeSingelton instatnce;

private UnThreadSafeSingelton() {
}

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

[i]线程安全[/i]

public class ThreadSafeSingelton {
private static ThreadSafeSingelton instatnce;

private ThreadSafeSingelton() {
}

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


[i]Double-Check Locking[/i]

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;
}
}

[i]Initialization on demand holder[/i]

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;
}
}

[i]Singleton的序列化[/i]

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;
}
}

[i]测试[/i]

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();
}
}

[b]Observer(观察者)模式[/b]
[i]普通观察者模式[/i]

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);
}
}

[i]Java标准库的观察者模式[/i]

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);
}
}
}


[b]Mediator(中介者)模式[/b]

[b]Proxy(代理)模式[/b]
[i]静态代理[/i]
[img]http://dl.iteye.com/upload/attachment/550262/dcd923a3-c3ca-30e8-9ddf-1ba035212365.png[/img]

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);
}
}

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

[b]Chain of Reponsibility(责任链)模式[/b]

[b]Flyweight(享员)模式[/b]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值