Java status mode sample code, java sample code

Source: Internet
Author: User

Java status mode sample code, java sample code

Package org. rui. pattern; import junit. framework. *;/*** in order to make the same method call generate different behaviors, the State mode switches the corresponding implementation (implementation) within * lifecycle of the proxy (surrogate ). When you find that a lot of testing is required before deciding how to implement any Object decoupling * method of http://blog.csdn.net/lxwde 28, this is a method to optimize the implementation code. For example, * the fairy tale Frog Prince contains an object (a creature). The behavior of this object depends on its own State. You can use a boolean value to indicate its status. The test program is as follows: ** @ author Administrator **/class Creature {private boolean isFrog = true; public void greet () {if (isFrog) System. out. println ("Ribbet! "); ElseSystem. out. println (" Darling! ");} Public void kiss () {isFrog = false;} public class KissingPrincess extends TestCase {Creature creature = new Creature (); public void test () {creature. greet (); creature. kiss (); creature. greet ();} public static void main (String args []) {junit. textui. testRunner. run (KissingPrincess. class );}}///:~

Package org. rui. pattern; import junit. framework. *;/*** state mode: changes the behavior of an object and an (state) object used to change the class. Signs: almost all methods contain (identical) conditions (expressions) code. * ** However, the greet () method (and all other methods that must test the isFrog value before the operation is completed) will eventually generate a lot of hard-to-handle code. * If you delegate these operations to a changeable State object, the code will be much simpler. ** @ Author Administrator **/class Creature2 {private interface State {String response ();} private class Frog implements State {public String response () {return "Ribbet! ";}} Private class Prince implements State {public String response () {return" Darling! ";}} Private State state = new Frog (); public void greet () {System. out. println (state. response ();} public void kiss () {// change object state = new Prince ();} public class KissingPrincess2 extends TestCase {Creature2 creature = new Creature2 (); public void test () {creature. greet (); creature. kiss (); creature. greet ();} public static void main (String args []) {junit. textui. testRunner. run (KissingPrincess2.class );}}///:~

Package org. rui. pattern; import org. junit. test; import junit. framework. *;/*** the following code demonstrates the basic structure of the State mode */interface State {void operation1 (); void operation2 (); void operation3 ();} class ServiceProvider {private State state State; public ServiceProvider (state State state) {this. state = state;} public void changeState (State newState) {state = newState; System. out. println ("========= changeState =============" + newState. getClass (). GetSimpleName ();} // implement public void service1 (){//... state. operation1 ();//... state. operation3 ();} public void service2 (){//... state. operation1 ();//... state. operation2 ();} public void service3 (){//... state. operation3 ();//... state. operation2 () ;}} class Implementation1 implements State {public void operation1 () {System. out. println ("Implementation1.operation1 ()");} public void operation2 () {System. Out. println ("Implementation1.operation2 ()");} public void operation3 () {System. out. println ("Implementation1.operation3 ()") ;}} class Implementation2 implements State {public void operation1 () {System. out. println ("Implementation2.operation1 ()");} public void operation2 () {System. out. println ("Implementation2.operation2 ()");} public void operation3 () {System. out. println ("Implementation2.operation3 ()") ;}} public Class StateDemo extends TestCase {static void run (ServiceProvider sp) {sp. service1 (); sp. service2 (); sp. service3 ();} ServiceProvider sp = new ServiceProvider (new Implementation1 (); @ Testpublic void test () {run (sp); sp. changeState (new Implementation2 (); run (sp);}/** public static void main (String args []) {* junit. textui. testRunner. run (StateDemo. class );}*/}///:~ /** In the main () function, the first implementation is used first, and then transferred to the second implementation. When you implement the State mode on your own, you will encounter many details. You must select an appropriate implementation method based on your needs, such as the State used) whether to be exposed to the called customer and how the status changes. In some cases (for example, Swing * LayoutManager), the client can directly upload objects, but in the example of KissingPrincess2.java, the status is invisible to the client. In addition, the mechanism used to change the State may be very simple and complicated-for example, the State Machine (State * Machine) to be mentioned later in this book ), there will be a series of States and different mechanisms for changing states. The LayoutManager example of Swing is very interesting. It also reflects the behavior of * Strategy Mode and State mode. The difference between the Proxy mode and the State mode is that they solve different problems. In design patterns, is this description * Common application of Proxy mode: 1. Remote Proxy provides a local Proxy for an object in different address spaces. RMI Compiler (rmic) automatically creates a remote proxy when creating * stubs and skeletons. 2. virtual proxy. When creating a complex object, use * "lazy initialization )". 3. protection proxy is used when you do not want the client programmer to fully control the proxied object. 4. smart reference. Provides additional actions when accessing the proxy object. * For example, it can be used to count the reference of a specific object to implement copy-on-write, thus avoiding the object alias (object aliasing ). simpler * an example is used to record the number of times a specific method is called. You can regard reference in java as a protection proxy, which controls the allocation) the actual object access (and you can ensure that you do not use a null reference )). "Rewrite: In design patterns, the Proxy mode and * State mode are considered irrelevant, because the structure provided in the book to implement these two modes is completely different (I think this implementation is a bit broken ). Especially in the State * mode, it uses a separation implementation hierarchy, but I don't think it is necessary at all, unless you decide that the implementation code is not controlled by you (of course, this is also a possible situation, but if * the code is controlled by you, it is more concise and practical to use a separate base class ). In addition, a public base class is not required for Proxy mode, because the Proxy object only controls access to the Proxy object. Despite the differences in segments, both the Proxy mode and the State * mode use a Proxy (surrogate) to pass the method call to the implementation object .』 */


Look for an example of a Java state mode application.

1. The State mode allows an "object" to change its behavior when its internal state changes.
2. Status mode roles:
Abstract state, specific State (usually several, with different behaviors under each State), environment (context) role (that is, the state of an object, generally, this object needs to initialize a state, change the state, and behavior in this state)

When we play basketball, athletes can be in normal, abnormal, and extraordinary states. Now we will take the status when we play basketball as an example,

First, we abstract the state and its behavior,
Interface State {
Public void shot ();
}
Then implement the specific state. Here we have three and three States.
Abnormal
Public class NonormalState implements State {
Public void shot (){
System. out. println ("Today you shot ten times ");
}
}
Normal:
Public class NormalState implements State {
Public void shot (){
System. out. println ("Today you shot five in ten ");
}
}
Extraordinary:
Public class SuperState implements State {
Public void shot (){
System. out. println ("You shot ten shots today ");
}
}
At this time, we come to an environment where an athlete is normal.
Public class Player {
Private State state State = new NormalState ();
Public void setState (State state State ){
This. state = state;
}
Public void shot (){
State. shot (); // here I feel like an Object Adapter IN THE create mode. This should be the case,
}
}
Test this example
Public class StateTest
{
Public static void main (String [] args ){
Player player = new Player ();
Player. shot (); // shooting normally
Player. setState (new NonormalState ());
Player. shot (); not shooting normally
Player. setState (new SuperState ());
Player. shot (); shooting under extraordinary circumstances
}
}

The design patterns in java are described in detail.

The Design pattern is derived from 23 Design Patterns mentioned in Design Patterns: Elements of Reusable Object-Oriented Software,

The 23 modes are divided into three categories based on the purpose of the model: Creational, Structural and Behavioral modes.

Creational ):
The creation mode is used to create objects. We often need to instantiate classes in coding. The creation mode provides various solutions to remove hard-coding from the instantiated code ), this makes encoding more flexible and general, and applies to more complex behaviors. Including Factory Method Abstract Factory Method Builder Pattern Prototype Pattern Singleton

Structural)
The structure mode processes the combination of classes or objects to obtain a larger structure. Including · Adapter pattern · Composite pattern, · Proxy pattern, · Flyweight pattern, · Fa çade pattern, · Bridge pattern, · Decorator pattern,

Behavioral)
How to interact with a behavior mode processing class or object, including: Observer pattern · Mediator · Memento · Chain of Responsibility · Template pattern · Interpreter in a program. · Strategy pattern · Visitor pattern · State pattern · Command pattern · Iterator pattern

Too many. I suggest you find this book for your own research, such as Java and pattern, Head first design pattern,
However, it is best to study the design mode when you are familiar with the language. Otherwise, it will make the code hard to read.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.