孩子这几天早上总是迟到

 这几天早上,孩子总是很迟才醒来,大概是8:30过后了。吃了饭收拾好,送到幼儿园差不多就9:30左右了。

实际上,孩子晚上一般是8:30左右就睡了,不会超过9:00,可是她就是早上不像原来那样醒得早了。不知是不是跟她这几天感冒有关系?

孩子前一段时间感冒了,吃了西药好得差不多了,但是这两天又有点鼻塞,流鼻涕。

还有,孩子现在吃西药有进步了。一般小粒的药丸她可以吞服了。但是大粒的还是必须碾细了用水兑服。

今天送孩子去看一下西医,等她感冒好了,再看是否能恢复原来的按时起床和上学。

还有,这学期孩子只报了一个美术兴趣班,我们本来想给她报的舞蹈兴趣班因为满员没有报成(她自己也好像对舞蹈有兴趣)。我看现在开始预交学费了,顺便关注一下下学期的兴趣班报名。

Thinking in Patterns chapter 19: Pattern refactoring

Thinking in Patterns with Java V0.9: chapter 19: Pattern refactoring:

TIPatterns.htm#_Toc41169793

1, Sections:

Pattern refactoring  181

Simulating the trash recycler. 182

Improving the design. 186

?Make more objects?. 186

A pattern for prototyping creation  189

Trash subclasses. 193

Parsing Trash from an external file  195

Recycling with prototyping. 198

Abstracting usage. 199

Multiple dispatching. 203

Implementing the double dispatch   204

The Visitor pattern. 211

A Reflective Decorator. 214

More coupling?. 219

RTTI considered harmful?. 220

Summary. 223

Exercises. 224

2, The main content and feeling:

This chapter foucuses on the applying of some patterns in the before chapters. With a trash recyleing system example, step by step, in an evoluting style, the book teachs me how to refine a system with design patterns by asking an important question in this processing: "what will change?" continuely.

The summary of this chapter is also the summary of design patterns given by the author. So, it worth to be read regularly later.

Here is some words about this summary:

1), "Design patterns in general strive to separate the things that change from the things that stay the same."

2), Finding the "vector of change" can be happened at any stage of a system's life. So, refining system may be happened through a system's life.

3), "What design patterns say is that OOP isn't just about polymorphism. It's about 'separating the things that change from the things that stay the same.'"

"But design patterns in general show other ways to accomplish the basic goal, and once your eyes have been opened to this you will begin to search for more creative designs."

4), Now, I make a review of how to refine a first-cut system step by step with design patterns in this book's trash recycling system.

(1), After the first-cut of "Simulating the trash recycler", the question to be raised:"What if the situation changes", for example, a new type trash called cardboard to be added into system, this will cause code less maintainable.

(2), So, "The solutions in Design Patterns are organized around the question

?What will change as this program evolves?? This is usually the most important

question that you can ask about any design. If you can build your system around

the answer, the results will be two-pronged: not only will your system allow

easy (and inexpensive) maintenance, but you might also produce components that

are reusable, so that other systems can be built more cheaply. "

"This brings up a general object-oriented design principle that I

first heard spoken by Grady Booch: 'If the design is too complicated, make more

objects.' "

Then a Messenger class to be created to encapsulate trash information, just the Messenger Pattern to be used here.

Then, the Factory Pattern to be used by "the only code that must be modified is within the factory, so the factory isolates the effect of that change."

 

For a more flexiable adding new trash type, the Prototype Pattern which hasn't been described in the previous chapters appears, it is just "The general idea is that you have a master sequence of objects, one of

each type you?re interested in making. The objects in this sequence are used

only for making new objects, using an operation that?s not unlike the clone( )

scheme built into Java?s root class Object. In this case, we?ll name the

cloning method tClone( ). When you?re ready to make a new object, presumably

you have some sort of information that establishes the type of object you want

to create, then you move through the master sequence comparing your information

with whatever appropriate information is in the prototype objects in the master

sequence. When you find one that matches your needs, you clone it."

But, in this example, the "master sequence of objects" doesn't hold "objects", they are Classes. And, with Java 1.1 reflection, these Class objects can be used to create the real object of that Class. Maybe, I have misunderstood "Prototype Pattern.

(3), But, "In terms of object creation, this design does indeed severely

localize the changes you need to make to add a new type to the system. However,

there?s a significant problem in the use of RTTI that shows up clearly here.

The program seems to run fine, and yet it never detects any cardboard, even

though there is cardboard in the list! This happens because of the use of RTTI,

which looks for only the types that you tell it to look for. The clue that RTTI

is being misused is that every type in the system is being tested, rather than

a single type or subset of types. As you will see later, there are ways to use

polymorphism instead when you?re testing for every type."

Because "RTTI is being misused", so we need step furthermore "So it?s worth trying to eliminate RTTI in this case, not just for aesthetic reasons?it produces more maintainable code."

(4), In the new implemetion of trash recyleing system: //: refactor:recycleb:RecycleB.java, "Adding new types to the system consists of adding or modifying distinct classes without causing code changes to be propagated throughout the system."

But, a further challenge be posted, RTTI "it should be eliminated altogether from the operation of sorting the trash into bins." I think to say it is because: "if(t.getClass().equals(type))" in the the code below:


  public boolean grab(Trash t) {

    // Comparing class types:

    if(t.getClass().equals(type)) {

      list.add(t);

      return true; // Object grabbed

    }

    return false; // Object not grabbed

  }

This code locates in //: refactor:recycleb:RecycleB.java.

Its meaning is "t.getClass()" is also a kind of RTTI? 

(5), So, the multiple dispatching to be used to "end up detecting some types manually and effectively producing your own dynamic

binding behavior" with "the polymorphism (dynamically-bound method calls) is to handle type-specific information for you."

Look at the code below, the multiple dispatching is used like this:

For trash:


interface TypedBinMember {

  // The new method:

  boolean addToBin(TypedBin[] tb);

} ///:~

For bin:


public abstract class TypedBin {

  Collection c = new ArrayList();

  protected boolean addIt(Trash t) {

    c.add(t);

    return true;

  }

  public Iterator iterator() {

    return c.iterator();

  }

  public boolean add(DDAluminum a) {

    return false;

  }

  public boolean add(DDPaper a) {

    return false;

  }

...

}

(6), "While previous versions of the trash sorting

example emphasized the addition of new types of Trash to the system,

TrashVisitor.java allows you to easily add new functionality without disturbing

the Trash hierarchy. There?s more code in TrashVisitor.java, but adding new

functionality to Visitor is cheap. If this is something that happens a lot,

then it?s worth the extra effort and code to make it happen more easily."

Here, the Vistor Pattern to be used for the reason above which be described in the summary of this chapter.

(7), Here, author tells me don't chase "Low coupling and high cohesion" too much :"Applied mindlessly, though, it can prevent you from achieving a more elegant design. It seems that some classes inevitably have a certain intimacy with each other. These often occur in pairs that could perhaps be called couplets;"

(8), At last, author tells me:"However, RTTI doesn?t automatically create non-extensible code. "

With right-use of "RTTI", //: refactor:dynatrash:DynaTrash.java

// Using a Map of Lists and RTTI to automatically sort

// trash into ArrayLists. This solution, despite the

// use of RTTI, is extensible.

And, it also is a beautiful design to use "a new tool will be introduced, which I call a TypeMap.", "This is certainly the smallest solution to the problem, and arguably the most elegant as well. It does rely heavily on RTTI,...".

It seems to tell me, with the good design, you can use almost any tool(technique) to build you system.

 

3, Questions about programming:

  1), return (Trash)ctor.newInstance(

            new Object[]{new Double(info.data)});

The process of calling

newInstance( ) extracts the double, but you can see it is a bit confusing?an

argument might be a double or a Double, but when you make the call you must

always pass in a Double. Fortunately, this issue exists only for the primitive

types.

  2),


public class Cardboard extends Trash {

  private static double val = 0.23f;

  public Cardboard(double wt) { super(wt); }

  public double getValue() { return val; }

  public static void setValue(double newVal) {

    val = newVal;

  }

} ///:~

A question: Can I put the code except constructor in such sub-class like above

into their super class: Trash and don't re-write them in all the sub-classes?

My researching:

Why don't do like below:


public abstract class Trash {

private double value;

private double weight;

public Trash(double val, double wt) {

value = val;

weight = wt;

}

public double getValue() {

return value;

}

public double getWeight() {

return weight;

}

}


public class Cardboard extends Trash {

  public Cardboard(double val, double wt) {

  super(val, wt);

  }

} ///:~

3),


//: refactor:doubledispatch:DDCardboard.java

// Cardboard for double dispatching.

package refactor.doubledispatch;

import refactor.trash.*;

 

public class DDCardboard extends Cardboard

    implements TypedBinMember {

  public DDCardboard(double wt) { super(wt); }

 

  public boolean addToBin(TypedBin[] tb) {

    for(int i = 0; i < tb.length; i++)

      if(tb[i].add(this))

        return true;

    return false;

  }

 

} ///:~

There is same code which be marked as red color in the above class as other classes like above, why don't put them into their base class?

There is an answer in the book:


But notice the argument: this. The type of this is different for each subclass of Trash, so the code is different.

But, I haven't understood very clearly, it needs more further learning for me.

4),

Of course, in this case it works well only if you’re adding new Visitors, but it gets in the way when you add new types of Trash.

4, Questions about english language:

1), Strange words:

 bin, Aluminum, branch off, silly, turn around, receptacle, enigma, commodity,

cardboard, definitely, recycling, appropriate, the results will be two-pronged,

promise, insight, refinement, would like, This is simultaneously counterintuitive and ludicrously simple, indirection, accidental, elevate, elaborate, eliminate, for that matter, presumably, work with, drop out, rectify, facilitate, severely, aesthetic, clue, be aware of,strictly,satisfactory, purist, altogether, dilemma, have control of, ease, Reflective, albeit, tally, inevitable, intimacy, in pairs, couplets, condemnation, ill-fated, stated, counterproductive, strive, analyst, about-face, syndrome, prohibitively, fame, proponent, autonomous,

2), Strange sentences:

 

 The extra constraint is that the trash arrives at the trash recycling plant all mixed together.

 (Indeed, this is the whole enigma of recycling).

(we?ve started referring to Messenger as a design pattern, but it?s simple enough that you may not choose to elevate it to that status).

then you move through the master sequence comparing your information with whatever appropriate information is in the prototype objects in the master sequence.(whatever?)

If it still can?t be found something is really wrong, but if

the load is successful then the factory method is called recursively to try

again.

Note that the benefit is helpful here but not exactly what we started out to accomplish, so at first blush you might decide that this isn’t the desired solution.

   incomplete

Java中的静态内部类(static inner class)

在学习Thinking in Patterns with Java的Pattern refactoring中的//: refactor:trash:Trash.java的源代码时,发现静态内部类的使用,如下:


//: refactor:trash:Trash.java

// Base class for Trash recycling examples.

package refactor.trash;

import java.util.*;

import java.lang.reflect.*;

public abstract class Trash {

  ...//略去部分代码

  public static class Messenger {

    public String id;

    public double data;

    public Messenger(String name, double val) {

      id = name;

      data = val;

    }

  }

  ...//略去部分代码

  public static Trash factory(Messenger info) {

    ...//略去部分代码

  }

} ///:~

后面使用Messager类是这样的:


Trash.factory(new Trash.Messenger(type, weight))

经过查阅资料,得出下面的理解:

1、为什么用内部类?

答:因为Messenger的作用仅是为产生Trash而使用来封装信息的辅助类,其它地方也用不着,所以放在Trash类的内部;

2、为什么用静态的内部类?

答:因为使用静态的内部类可以在其包含它的外部类没有生成实际对象时生成这个内部类,而在这里,在Messenger对象生成之前根本就不能生成它的外部类Trash的对象;就算是其它某种情况可以先生成外部类,如果没有先生成外部类的必要性,我认为,应该尽量使用静态内部类,因为,何必要生成一个没有用的多余的外部类对象呢?(这个观点没有深入的的学习和验证,也许不正确!

参考资料:

1、Thinking in Java, 3rd ed. Revision 4.0 Nested classes

./aaa-TIJ3-distribution/html/TIJ310.htm#Heading7630


when you say an inner class is static. A nested class means: Feedback

   1. You don’t need an outer-class object in order to create an object of a nested class. Feedback

   2. You can’t access a non-static outer-class object from an object of a nested class. Feedback

2、一篇完整叙述Java内部类的文章:

转:java内部类

你有两个选择(转自朋友的邮件)

转载者前言:

太多的时候,我们都不能改变客观环境,但我们可以自由的改变思考的角度和主观心情。我觉得,人生快乐与否很大程度上取决于自己是否会进行选择:您可以选择快乐,也可以选择痛苦。就这么简单。

转帖正文,后附朋友发送的ppt演示文档。在此感谢这位朋友发来这么好的东西。并与所有朋友分享。

×××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××

Jerry是美国一家餐厅的经理,他总是心情非常好,

当别人问他最近过得如何时,

他总是有好消息同大家说。

他总是回答:

『我一直都很幸福!』

当他换工作的时候,

许多服务生都跟着他

从这家餐厅换到另一家。

为什么呢?

因为Jerry是个天生的激励者!

如果有某位员工今天运气不好,

Jerry总是适时地告诉那位员工

往好的方面想。

看到这样的情境,真的让我很好奇,所以有一天我到Jerry那儿问他:

我不懂,没有人能够老是那样地积极乐观,你是怎么办到的?

Jerry回答:

『每天早上,当我起来的时候我告诉自己:

我今天有两种选择 ,

我可以选择好心情,

或者我可以选择坏心情。

 

我总是选择好心情』

『即使有不好的事发生,

我可以选择做个受害者,

或是选择从中学习,

我总是选择从中学习。 』

『每当有人跑来跟我抱怨,

 我可以选择接受抱怨

或者指出生命的光明面,

我总是选择生命的光明面。』

但并不是每件事都那么容易啊!

   生命就是一连串的选择,

每个状况都是一个选择,

你选择如何回应,

你选择人们如何影响你的心情

你选择处于好心情或是坏心情

   你选择如何过你的生活。

数年后

有一天,

我听到Jerry意外地做了一件

意想不到的事:

有一天他忘记关上餐厅的后门,

结果

早上,三个武装歹徒闯入抢劫,

他们要Jerry打开保险箱。

但由于过度紧张,Jerry弄错了一个号码,造成抢匪的惊慌,开枪射击Jerry

幸运地,

Jerry很快地被邻居发现,紧急送到医院抢救

经过18小时的外科手术

以及细致照顾,

Jerry终于出院了。

还有颗子弹留在他身上……

事件发生6个月之后

我遇到Jerry,

我问他最近怎么样

他回答:

『我一直都很幸福!要看看我的伤疤吗?』

我婉拒了。

但我问他当抢匪闯入的时候,他的心路历程。

Jerry答道:

『我第一件想到的事情是我应该锁后门的,当他们击中我之后,我躺在地板上,还记得我有2个选择:我可以选择生,或选择死。我选择活下去』

你不害怕吗?

 Jerry继续说:

『医护人员真了不起,他们一直告诉我没事,放心。 』

『但是在他们推我去急救室路上的时候,

我看到医生跟护士脸上忧郁的神情,

我真的被吓坏了』

『他们的眼睛里好像写着:

他已经是个死人了,我知道我需要采取行动。 』

   当时你做了什么?

Jerry继续说:

『当时有个挺胖的护士大声地问我,

她问我是否会对什么东西过敏?』

『我回答:有。这时医生跟护士都停下来等待我的回答。我深深地吸了一口气,』

 『接着说:子弹!』

 『听他们笑完之后我告诉他们:

我现在选择活下去,请把我当作一个活生生的人来开刀,不是一个活死人。 』

Jerry能活下去当然要归功于医生的精湛医术,但同时也由于他令人惊异的态度。

每天你都能选择享受你的生命,或是憎恨它。

这是唯一一件真正属于你的权利,

没有人能够控制或夺去的东西

                    

如果你能时时注意这些愉快的事情,

现在你有两个选择:

1、你可以遗忘这故事

2、将这传递给你关心的人

      我选择了2

   希望你也是如此!

附件:你有两个选择.ppt,86528 bytes

×××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××

                                            转载完毕

参加幼儿园本学期末的家长会

今天下午,去孩子幼儿园的教室里开了家长会。本来,孩子们有两位老师的,因为唐老师生病了,就只有赵老师在班上了。

先是园领导的电视讲话,主要是介绍幼儿园的教职园工状况,比较有印象的几句话是:老师都崇尚终身学习,老师的学术交流和老带新的工作比较有特色。。。

然后是赵老师介绍孩子们在园里的生活学习情况,并比较系统的讲了孩子们在中班年龄段的特点是:集体意识增强,自制能力增强。。。

还有本班孩子的一些优点和缺点,优点是孩子们都比较听话,还有行为习惯方面要加强。会上还发了家长对老师的评论表格。

我比较感兴趣的是赵老师介绍的幼儿园的新教材和一套新的幼教理论:整合式教学。大意是围绕某一项主题,在各个角度充分发挥这个主题,训练孩子在语言、数理逻辑、身体运动等各方面的能力。以“伞的世界”为例,赵老师发给我们一张“课程单元网络”图和一张“课程生成树”图,很有意思。对我们成人世界的学习也很有启发。有机会把这两张图扫描下来传上来。

这半年来,我对孩子、孩子的老师和幼儿园都比较满意。幼儿园的老师都很有爱心,很受孩子的爱戴。有时,孩子从幼儿园回来会很突然地对我们说:我以后不骂人了,骂人不是好孩子。。。我估计,老师在在幼儿园里给孩子们上了课。在这方面,我感觉老师的力量大于我们家长的作用。就我的经验而言,要想让孩子主动承认自己的错误很难。也许,是我的方法有问题。

今天,我们的孩子还得了一个表扬,与几个孩子一起被特别的提出来表扬爱收拾东西,课桌整洁。我的心里听着美滋滋的。

像赵老师讲的,孩子的行为习惯还要进一步加强。还有,我这学期对孩子的学习具体内容还关心得不够。孩子在幼儿园里具体学了些什么,以什么方式学的,学的效果怎么样,以后还要更多的关心。另外,孩子的书写能力也要加强。她喜欢画画,对这一兴趣也要更多的引导。赵老师说画画对孩子的能力培养比较有效,我表示赞同。

当然,这一切不能破坏了“快乐的童年”这一主旋律。孩子,还是以玩为主,以培养良好行为习惯为主,我以为。

附:

1)、“课程生成树”图

[img]http://java.learndiary.com/upload/2007/1/13/1168657409546_1523DtBq.jpg[/img

2)、“课程单元网络”图

[img]http://java.learndiary.com/upload/2007/1/13/1168657429984_RVqBKoUi.jpg[/img

UML建模中的状态图及状态图建模原则示例摘要(转摘)

在学习Thinking in Patterns chapter 18: Complex system states中的StateMachine的前半部分时(TIPatterns.htm#_Toc41169779),与我原来看那本System Analysis and Design中文译本中的UML建模中的状态图作了一下比较。发现二者有比较大的区别,故把状态图的有关知识再复习了一下。

下面是我在网上搜索到的一篇讲述UML状态图的文章,其中对状态图的基本定义和它在实际应用中的示例和原则都作了详细的阐述。不过比较长,而且是翻译过来的,很不好理解。尤其是前半部分讲基础概念的,更是模模糊糊的。我根据自己的需要,把上面的内容摘录了一些提纲性的东西备用。

一、基础部分

  状态图(Statechart Diagram)是描述一个实体基于事件反应的动态行为,显示了该实体如何根据当前所处的状态对不同的时间做出反应的。通常我们创建一个UML状态图是为了以下的研究目的:研究类、角色、子系统、或组件的复杂行为。

 

  状态机由状态组成,各状态由转移链接在一起。状态是对象执行某项活动或等待某个事件时的条件。转移是两个状态之间的关系,它由某个事件触发,然后执行特定的操作或评估并导致特定的结束状态。图 1 描绘了状态机的各种元素。

  状态机的要素:(图 1:状态机符号。)

  状态的要素:


名称:            将一个状态与其他状态区分开来的文本字符串;状态也可能是匿名的,这表示它没有名称。

进入/退出操作:    在进入和退出状态时所执行的操作。

内部转移:        在不使状态发生变更的情况下进行的转移。

子状态:          状态的嵌套结构,包括不相连的(依次处于活动状态的)或并行的(同时处于活动状态的)子状态。

延迟的事件:      未在该状态中处理但被延迟处理(即列队等待由另一个状态中的对象来处理)的一系列事件。

  转移的要素:


源状态:            转移所影响的状态;如果对象处于源状态,当对象收到转移的触发事件并且满足警戒条件(如果有)时,就可能会触发输出转移。

事件触发器:        使转移满足触发条件的事件。当处于源状态的对象收到该事件时(假设已满足其警戒条件),就可能会触发转移。

警戒条件:          一种布尔表达式。在接收到事件触发器而触发转移时,将对该表达式求值;如果该表达式求值结果为 True,则说明转移符合触发条件;如果该表达式求值结果为 False,则不触发转移。如果没有其他转移可以由同一事件来触发,该事件就将被丢弃。

操作:              可执行的、不可分割的计算过程,该计算可能直接作用于拥有状态机的对象,也可能间接作用于该对象可见的其他对象。

目标状态:          在完成转移后被激活的状态。

二、应用示例部分(结合示例讲了画状态图的一些准则):

  我觉得文中的这个示例太好了,值得经常看看。

1、通用准则

  1.1)、当行为的改变和状态有关时才创建状态图

  敏捷建模( AM) ( Ambler 2002)的原则--最大化项目干系人的投资--建议你只有当模型能够提供正面价值的时候才创建模型。

   

图⒈班级注册的一个UML状态图。

  1.2)、把初始状态放置在左上角。

  1.3)、把最终状态放置在右下角。

2、状态指南

  状态是一个实体的行为模式的某个阶段。 状态的表示是通过实体的属性值。

  2.1)、状态名称要简单但应具有描述性。

  2.2)、避免"黑洞"状态。

  2.3)、避免"奇迹"状态。

3、子状态建模指南

  3.1)、为复杂的目标建模子状态。

图⒉Seminar的完整生命周期

  3.2)、把通用的子状态变换放在一起

  3.3)、为复杂的实体创建一个分层的状态图

图⒊Seminar的高阶状态图。

  3.4)、最高阶的状态图总有初始态和最终态

4、变换和动作

  变换是从一种状态到另一种状态的序列,它可能是通过一个事件触发的。

  4.1)、用实现语言的命名规则命名软件动作

  4.2)、只有对所有的入口变换都合适时才注明入口动作

  4.3)、只有对所有的出口变换适合时才注明出口动作

  4.4)、出口动作,用exit/标记来表示,工作方式类似于入口动作。

  4.5)、只有当你想终止并再进入该状态时才建模递归变换

  4.6)、用过去式命名转换事件

  4.7)、把转换标记放在接近源状态的地方

  4.8)、以转换方向为基础放置变换标记

    4.9)、为了更易于判断哪个标记和变换是一起的,按照如下的规则来放置变换标记:

      4.9.1)、在变换线条上的从左到右。

      4.9.2)、在变换线条下的从右到左。

      4.9.3)、变换线条右边的往下。

      4.9.4)、变换线条左边的往上。

5、警戒点

  一个警戒点是为了穿过一个转换而必须为真的一个条件。

  5.1)、警戒点不应该重叠

  5.2)、为可视化的定位警戒点而引入接合点。

  5.3)、警戒点不必配套

  5.4)、一致的命名警戒点

××××××××××××××××××××××××××××××××××××××××××××××××××××××××××

                          摘录完毕

Thinking in Patterns chapter 18: Complex system states

Thinking in Patterns with Java V0.9: chapter 18: Complex system states: TIPatterns.htm#_Toc41169778

1, Sections:

Complex system states  159

  StateMachine. 159

    Exercises. 169

  Table-Driven State Machine. 169

    The State class. 171

    Conditions for transition. 172

    Transition actions. 172

    The table. 172

    The basic machine. 173

    Simple vending machine. 174

    Testing the machine. 179

  Tools. 180

  Table-driven code: configuration flexibility  180

    Table-driven code using anonymous inner classes  180

  Exercises. 180

2, The main content and feeling:

 

  Although I have been stopped at this chapter and State chart Diagram in UML

two or three days, there are still some questions left. But, I can't stay here

too long, there are many need to read, so, left some questions here, maybe

they will be resolved in the "future".

First of all, I found there isn't a pattern called "StateMachine Pattern" in

GoF's book except a pattern called "state pattern". Maybe, this is a design pattern invented by Bruce, just like the words below:


This method not only moves to the next state, but it also calls run( ) for each state object ? thus you can see it?s an expansion of the idea of the State pattern, since run( ) does something different depending on the state that the system is in.

What is Bruce's "StateMachine Pattern"?

He tells us:


While State has a way to allow the client programmer to change the

implementation, StateMachine imposes a structure to automatically change the

implementation from one object to the next.

There are two types of "StateMachine Pattern" implementation in this book.

The first is called "StateMachine" simplily, and second is called "Table-Driven State Machine". When I read these two "statemachine", I compared them with the State chart Diagram in UML I have learned before. So I found some question I can't answer. Below is my understanding for these two Bruce's StateMachine.

At first, give my understanding about State chart Diagram in UML, I like its

OOP style, even I maybe missunderstood it, I put my understanding here, wish

someone can point out my error.

A State chart Diagram can be owned by an entity(for example, an object of a

class ), if the entity's action dependents on what state the entity is in, then a state chart diagram may be needed.

For me, the most important understanding about this is the transition between

two states. Three things can be in a transition: event, just a call to this

object's method or a message send to this object; guard condition, only it is

"true" can event cause a state's change; action, just some processes in

object's method or some messages send to other objects to perform somethings during this transition.

Then, bring the idea of UML's state chart diagram in my mind, I look at Bruce's first "StateMachine".

In this statemachine, all is focus on the state class. state class performace

some actions in the transition SHOULD before this state, state class recieve an input

and decide which state is the next state.

Just like below:


public interface State {

  void run();

  State next(Input i);

} ///:~

Why do I say "state class performace some actions in the transition SHOULD before this state"?

Because I read some in this book like below:


 and as that transition is made some kind of action occurs (in the previous state machine design, this was the run( ) method):

I try to model the example of "statemachine" with UML's state chart diagram,

but I failed. Because the state object has done all the things, and the owner of

state objects has nothing to do. I can't send the owner a message which should

be a method of the owner to make a transition!

And another question in the example is:


class Waiting implements State {

  public void run() {

    System.out.println(

      "Waiting: Broadcasting cheese smell");

  }

  public State next(Input i) {

    MouseAction ma = (MouseAction)i;

    if(ma.equals(MouseAction.appears))

      return MouseTrap.luring;

    return MouseTrap.waiting;

  }

}

Why is "Waiting: Broadcasting cheese smell" in the run() method, but not

"Wait: Broadcast cheese smell"? Does it indicate a state or an action during transition before this state? I am a little confusing.

And, from the State chart diagram's definition, an action should be occured

before current state appeared in this example, but I don't know why it happens

as a run() method in a state object, just like below:


  public final void runAll(Iterator inputs) {

    while(inputs.hasNext()) {

      Input i = (Input)inputs.next();

      System.out.println(i);

      currentState = currentState.next(i);

      currentState.run();

    }

Next, from section "Table-Driven State Machine" I can draw example's State

chart Diagram using UML tool.

In this example, the state class can't do something like above's example, and,

an object called stateMachine holds every thing. I can send this stateMachine

a message: nextState(input: Input), this just a event cause the state's

change; And, when this transition is made, an action occurs by nextState()

to call another object's method: Transition.transition(input: Input), or the

stateMachine object just send a message to trasition object to do some actions.

Maybe, this just is the meaning of Bruce's words: "The classic state-transition diagram".

Maybe, Bruce's statemachine is from the aspect of using purpose, all these examples are focusing on how to design a statemachine conveniently; But I focus on if these "statemachine" are real "StateMachine" defined in UML.

Maybe, I have misunderstood all the UML's "statemachine" and the

"statemachine" in this book's example. If any of these case, please give me a

hint. My english is also very poor, if there are some thing unclear, please

let ne know. Thanks.

3, Questions about programming:

Many questions has been written above. Except above, There are entire section

I can't understand just below:


(Simple State Machine Diagram)

Goals:

·         Direct translation of state diagram

·         Vector of change: the state diagram representation

·         Reasonable implementation

·         No excess of states (you could represent every single change with a new state)

·         Simplicity and flexibility

Observations:

·         States are trivial – no information or functions/data, just an identity

·         Not like the State pattern!

·         The machine governs the move from state to state

·         Similar to flyweight

·         Each state may move to many others

·         Condition & action functions must also be external to states

·         Centralize description in a single table containing all variations, for ease of configuration

Example:

·         State Machine & Table-Driven Code

·         Implements a vending machine

·         Uses several other patterns

·         Separates common state-machine code from specific application (like template method)

·         Each input causes a seek for appropriate solution (like chain of responsibility)

·         Tests and transitions are encapsulated in function objects (objects that hold functions)

·         Java constraint: methods are not first-class objects

And, I almost can't see the picture after this section.

4, Questions about english language:

1), Strange words:

  impose, tagging, conceivably, mousetrap, theWhiW,

2), Strange sentences:

 // A State has an operation, and can be moved

 // into the next State given an Input:

This is typical, but certainly not required ? you could concievably want to override it, but typically the behavior change will occur in State?s run( ) instead.

   incomplete

Thinking in Patterns chapter 17: Multiple languages

Thinking in Patterns with Java V0.9: chapter 17: Multiple languages: TIPatterns.htm#_Toc41169757

1, Sections:

Multiple languages  120

  Interpreter motivation. 121

  Python overview.. 122

    Built-in containers. 123

    Functions. 124

    Strings. 125

    Classes. 127

  Creating a language. 130

  Controlling the interpreter. 134

    Putting data in. 134

    Getting data out. 140

    Multiple interpreters. 143

  Controlling Java from Jython  144

    Inner Classes. 148

  Using Java libraries. 148

    Inheriting from Java library classes  150

  Creating Java classes with Jython  151

    Building the Java classes from the Python code  156

  The Java-Python Extension (JPE)  157

  Summary. 157

  Exercises

2, The main content and feeling:

  First at all, let me remember a fact, this book is written at 3 years ago,

too many changes has been taken, so I think the language Python introduced

by Bruce in this book has many changes. And, there are many kinds of other languages maybe has present.

  Then, let us see what has been told in this chapter.

  At last, two days' reading without installing Python or Jython, I get a

conclusion: Python, maybe is the best lovely program language of Bruce's. The

most part of this chapter is introducing Python. On the other hand, the Interpreter Pattern in this Design patterns book is a little part of this chapter.

 

  What is Interpreter Pattern?

  It says:

 


  Sometimes the end users of your application (rather than the programmers of

that application) need complete flexibility in the way that they configure

some aspect of the program. That is, they need to do some kind of simple

programming. The interpreter pattern provides this flexibility by adding a

language interpreter.

 

  Note, although in almost all applications there are some factors that end

user can change it by some ways, for example, input something or press some

buttons, etc.. But, in a interpreter pattern, it provides end users the most probability for custom there many factors by simple programming.

  And, a ready for use this kind of Interpreter system introduced by Bruce is

Jython, a pure Java implementation of Python language. Of course, you can

write your own Interpreter sytem. But it seems too unecessary.

  Along with Bruce's lines, I got some about Python and Jython, and this is

almost real the first touch of this language for me. I can understand little

 bit of examples in this book without to run it under *ython.

  Use some sentences in this book to summary the understanding for *ython of

mine.

 


Python is a language that is very easy to learn, very logical to read

and write, supports functions and objects, has a large set of available

libraries, and runs on virtually every platform.

 

 


 It is marvelous for scripting, and you may find yourself

replacing all your batch files, shell scripts, and simple programs with Python

scripts. But it is far more than a scripting language.

 

 ...

 If you program with *ython, no redundant charactor typing. And it can be

worked together with java very well. All the Jython class and Java class can

almost interact without any problem. And, if you need native Python program

interact with Java, a resolution called The Java-Python Extension (JPE) can be

used.

  In this book, Bruce says maybe a new Design Pattern called Multiple Language

can be invented. In this way, mixing languages to resolve a question can be

better than using only one language. All the languages has its advantage and

shortage, mix them is a good idea.

  Bruce says:

 


  To me, Python and Java present a very potent combination for program

development because of Java?s architecture and tool set, and Python?s

extremely rapid development (generally considered to be 5-10 times faster than C++ or Java).

 

  But, I doubt that "5-10 times faster than C++ or Java", although I am not a

professional programmer(I don't work in IT), I think it is impossible that a

language has 5-10 times development speed than others. Because, building an

application need not only coding, but also many other works. I suppose, Python is good at coding, at building a good classes system, but, what classes are we need? How do they interact with each other? etc.. These kind of things is can't be reduced many only by a language.

 But, maybe, "Python?s extremely rapid development" is only refer to coding,

and mix this coding process with "Java's architecture" which is good at

building system architecture.

3, Questions about programming:

  1), if you create fields using the C++/Java style, they implicitly become static fields.

  2),

In addition, Jython’s JavaBean awareness means that a call to any method with a name that begins with “set” can be replaced with an assignment, as you can see above.

You are not required to inherit from Object; any other Java class will do.

Note that it?s important that the directory where the target lives be specified, so that the makefile will create the Java program with the minimum necessary amount of rebuilding.

4, Questions about english language:

1), Strange words:

 advantageous, arbitrarily, stuck, tedious, Interpreter, distraction, for-profit, royalties, basically, incorporating, scales up, purity, referred to, marvelous, affirmative, subsequent, add-on, acknowledged, associative, formalize, takes on, imitate, verbiage, signature, other than, tuple, control over, decimal place, spare, set off,  turns out to be,  aggressively, albeit, penchant, comma, from within, deceptively, thorough, further down, ambiguous, back and forth, it is worth noting that, disposal, endearing, intuitively, awareness, automated, shorthand, presumably,

come over, lambda, succinct, hood, frustrating, stem from, arguably, lurking,

potent, flesh out, terrific, leverage

2), Strange sentences:

 Indenting can nest to any level, just like curly braces in C++ or Java, but unlike those languages there is no option (and no argument) about where the braces are placed  the compiler forces everyone’s code to be formatted the same way, which is one of the main reasons for Python’s consistent readability.

 Note that Python was not named after the snake, but rather the Monty Python comedy troupe, and so examples are virtually required to include Python-esque references.

   incomplete

Thinking in Patterns Chapter 16: Complex interactions

Thinking in Patterns with Java V0.9: Chapter 16: Complex interactions: TIPatterns.htm#_Toc41169753

 1, Sections:

Externalizing object state  113

  Memento. 113

Complex interactions  114

  Multiple dispatching. 114

  Visitor, a type of multiple dispatching  117

  Exercises

2, The main content and feeling:

  Memento Pattern isn't described in this book(So I don't write a diary of Chapter 16: Externalizing object state), I must learn it in other place.

 

  After twice reading of chapter: Complex interactions, I got little from the book. Don't like Thinking in Java, in that book, there is detail explaination after every example. But, it isn't given explaination in this chapter's two examples. This book is only Version0.9.

  1), What is Multiple dispatching? I knew it from this point: "Remember that polymorphism can occur only via member function calls, if you want double dispatching to occur, there must be two member function calls: the first to determine the first unknown type, and the second to determine the second unknown type." 

  Just describe it use the example in the book below:


class Scissors implements Item {

  public Outcome compete(Item it) { return it.eval(this); }

  public Outcome eval(Paper p) { return Outcome.LOSE; }

  // ...

}


class Paper implements Item {

  public Outcome compete(Item it) { return it.eval(this); }

  public Outcome eval(Paper p) { return Outcome.DRAW; }

  //..

}

  Here, a scissors vs. a paper:

  s Item = new Scissors();

  p Item = new Paper();

  s.compete(p); // the first(method compete()) to determine the first unknown type(Scissors),

 

  //In the method "compete()", the second method is called

  p.eval(s);// the second(method eval()) to determine the second unknown type(Paper),

  Why does the first(method compete()) NOT to determine the second unknown type(Paper)?

  The key is this statement above:

  polymorphism can occur only via member function calls

  When the method compete() be called, the type of the object that call this method is determined, "Item" "s" is a "Scissors".

  The second method eval() is same as the first method complete().

  2), Visitor, a type of multiple dispatching

 

  After know the Mutiple dispatching, Vistor Pattern is understood soon. Because, it "builds on the double dispatching scheme shown in the last section".

  There is a point need to note, the purpose of using Vistor Patterns is changing the method's behavior without modifying original hierarchy.

  I explain this using the example in the book too:

  In this example, Flower classes hierarchy can't be changed. And can determining it's type by calling it's method: accept(Visitor v);

 

  Although Flower classes herarchy can't be changed, but Visitor classes herarchy can be changed, so there are two types of Visitor be created, one is "StringVal", another is "Bee". And, the second Type be determined in this method below:

  v.visit(this); //"this" is a Flower, when the "v" call visit() method, its type be termined. And, different type Vistor visit(this) can get different behavior, that just we want to get.

  3), Multiple dispatching can be replaced by a table lookup, just look it in the exercise 3.

  I think there are two type of Map will be used. it is one: key is class, value is another map; another map: key is class, value is outcome.

  4), At this point, I suddenly think, I guess, Bruce thinks the Design Pattern isn't a very import thing in his software design, I feel his words outside this book is just saying: many of these "Dsign Patterns" is redundant, a basic idea of mine be divided into these too many Patterns, this basic idea is: No pattern is patterns for all.

  This is only my guess, my feeling. If my feeling is right, maybe, we maybe can't see a version1.0 of this book:(

  My english language and program knowledge is poor, if I make any mistake, please tell me: mdx-xx@tom.com

 

3, Questions about programming:

  1), The answer starts with something you probably don’t think about: Java performs only single dispatching. That is, if you are performing an operation on more than one object whose type is unknown, Java can invoke the dynamic binding mechanism on only one of those types. This doesn’t solve the problem, so you end up detecting some types manually and effectively producing your own dynamic binding behavior.

  2), How to do if there are more than double dispatching in the above?

  Like below?

  a.F(b);

  b.G(c);

  c.H(a);

  ...

  3), All the exercises.

 

4, Questions about english language:

1), Strange words:

 compete, Scissors, Outcome, primary, dilemma, virtualize, bound, Gladiolus, Runuculus, Chrysanthemum, Inhabitant, Dwarf, Elf, Troll, Jargon, InventFeature,

Each Inhabitant can randomly produce a Weapon using getWeapon( ): a Dwarf uses Jargon or Play, an Elf uses InventFeature or SellImaginaryProduct, and a Troll uses Edict and Schedule.

syntactic, simplicity,

2), Difficult sentences:

The easiest way to do this is to create a Map of Maps, with the key of each Map the class of each object.

 

******************************************************************

The class diagrams of two examples in the book:

1),//: multipledispatch:PaperScissorsRock.java

2),//: visitor:BeeAndFlowers.java



 

    incomplete