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