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