码迷,mamicode.com
首页 > 编程语言 > 详细

Java中的复杂初始化

时间:2014-09-14 19:21:07      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   java   ar   strong   art   

虽然无聊,还是列出来。

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表达式后面的{{ ;}}; 
类体外的初始化块。


Java中的复杂初始化

标签:style   blog   http   color   使用   java   ar   strong   art   

原文地址:http://blog.csdn.net/yqj2065/article/details/39271859

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!