Java中的复杂初始化

来源:互联网 发布:mac 10 少女前线 编辑:程序博客网 时间:2024/05/19 10:08

虽然无聊,还是列出来。

6.1备忘录模式(5.6)中,Memento1的代码

例程 7-2 不变类package intent.memento;public final class Memento1{    private final VirtualState state;//要记忆的状态,    public Memento1(State state){        this.state =new VirtualState(state) ;    }    State getState(){        State state = new State(this.state.x,this.state.y);        return state;    }        /**     * 可以使用深克隆技术。     */    class VirtualState{        private int x;        private int y ;         public VirtualState(State state){            x = state.getX();            y = state.getY();        }            }}
程序中的VirtualState意在提醒程序员,此时保存的状态不是Originator的成员state同一个对象。

实际上,yqj2065是绝对不会设计一个多余的类滴,还是用State好。

于是,有了对应的代码:

package intent.memento;public final class Memento2{    private final State state;//要记忆的状态,    public Memento2(State state){              this.state =new State(){{setX(state.getX());setY(state.getY());}};    }    State getState(){        return new State(){{setX(state.getX());setY(state.getY());}};    }}
这里的一个无聊的东西
new State(){{setX(state.getX());setY(state.getY());}};
在《编程导论(Java)》p80,也提到了一下,new表达式后面的{{ ;}}; 
类体外的初始化块。


0 0
原创粉丝点击