您的位置:首页 > 编程语言 > Java开发

java 设计模式之单利模式以及代理模式(静态)

2013-11-26 17:19 686 查看
1:单利模式:

public class Singleton {

private static Singleton uniqueInstance = null;

private Singleton() {

// Exists only to defeat instantiation.

}

public static Singleton getInstance() {

if (uniqueInstance == null) {

uniqueInstance = new Singleton();

}

return uniqueInstance;

}

// Other methods...

}

代理模式(静态):

package com;

/**
* 车站接口-【抽象角色】
*
* @author abing
*
*/
interface Station {
void sellTicks();// 卖票
void transport();// 运输乘客
}

/**
* 火车站实现类-【具体角色】
*
* @author abing
*
*/
class TrainStationImpl implements Station {

@Override
public void sellTicks() {
System.out.println("TrainStation sell tickets");

}

@Override
public void transport() {
System.out.println("TrainStation transport passenger");

}
}

/**
* 该类做为火车站的一个代理直接供客户端调用-【代理角色】
*
* @author abing
*
*/
class StationProxy implements Station {
Station sta = new TrainStationImpl();

@Override
public void sellTicks() {
sta.sellTicks();//代理类中调用真实角色的方法。
}
public void otherOperate() {
System.out.println("do some other things...");
}
@Override
public void transport() {
System.out.println("StationProxy can not transport");
}
}

/**
* 客户端测试类
*
* @author abing
*
*/
public class StaticProxyDemo {
public static void main(String[] args) {
Station station = new StationProxy();//客户端直接操作代理类,避免了客户端与真实类的直接交涉
station.sellTicks();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: