background image

25
26

  

//作为私有内部类的备忘录角色,它实现了窄接口,可以看到在第二种方法中宽接

口已经不再需要

27

  //注意:里面的属性和方法都是私有的

28
29

  

private

 

class

 Memento 

implements

 MementoIF{

30

   

private

 

int

 state ;

31

   

private

 Memento(

int

 state){

32

    

this

.state = state ; 

33

   }

34
35

   

private

 

int

 getState(){

36

    

return

 state; 

37

   } 

38

  }

39

 }

40
41

 

//

——

测试代码

客户程序

42
43

 

public

 

class

 TestInnerClass{

44

  

public

 

static

 

void

 main(String[] args){

45

   Originator o = 

new

 Originator(); 

46

   o.createMemento();

47

   o.modifyState4Test(80);

48

   o.setMemento();

49

  }

50

 }

51
52

 

//窄接口

53
54

 

interface

 MementoIF{}

55
56

 

//“

备忘录管理者角色

57
58

 

class

 Caretaker{

59

  

private

 MementoIF m ;

60

  

public

 

void

 saveMemento(MementoIF m){

61

   

this

.m = m; 

62

  }

63

  

public

 MementoIF getMemento(){

64

   

return

 m; 

65

  }