初步理解
就是对类的访问多了一个代理类,不用直接操作类。从实例化的角度看,如果有实例存在就用已经存在的,节省资源。
主要三个类: 接口,实现类,代理类。
代码:
- 接口类
public interface IGame{
void play();
}
- 接口实现类
public class Game implements IGame{
private String gameName;
public Game (String gameName){
this.gameName= gameName;
startGame(gameName);
}
@Override
public void play() {
System.out.println("Playing " + gameName);
}
private void startGame(String gameName){
System.out.println("Starting " + gameName);
}
}
- 代理类
public class ProxyGame implements IGame{
private Game game;
private String gameName;
public ProxyGame(String gameName){
this.gameName= gameName;
}
@Override
public void play() {
if(game == null){
game = new Game(gameName);
}
game.play();
}
}