20 of 23 Design Patterns in Java-memo mode (memento pattern)

Source: Internet
Author: User

Abstract class Health
{
private int blood;
private int mana;
public void Setblood (int blood)
{
This.blood=blood;
}
public int Getblood ()
{
return blood;
}
public void Setmana (int mana)
{
This.mana=mana;
}
public int Getmana ()
{
return mana;
}

Public abstract Memento Creatememento ();
}

Class Memento extends Health
{
Public Memento Creatememento ()
{
System.out.println ("nothing");
return null;
}
}

Class Player extends Health
{
Public Memento Creatememento ()
{
Memento amemento=new Memento ();
Amemento.setblood (This.getblood ());
Amemento.setmana (This.getmana ());
return amemento;
}
public void Retorehealth (Memento Memento)
{
This.setblood (Memento.getblood ());
This.setmana (Memento.getmana ());
}
}

Class Taker
{
Memento memento=new Memento ();
public void Save (Memento Memento)
{
This.memento=memento;
}
Public Memento Restore ()
{
return this.memento;
}
}

public class Mementopatterntest
{
public static void Main (string[] args)
{
Player Aplayer=new player ();
Aplayer.setblood (99);
Aplayer.setmana (49);
System.out.println ("Before player Blood:" +aplayer.getblood () + ", Mana:" +aplayer.getmana ());

Taker ataker=new Taker ();
Ataker.save (Aplayer.creatememento ());

Aplayer.setblood (1);
Aplayer.setmana (2);
System.out.println ("After PK player Blood:" +aplayer.getblood () + ", Mana:" +aplayer.getmana ());

Aplayer.retorehealth (Ataker.restore ());

System.out.println ("After Retore player Blood:" +aplayer.getblood () + ", Mana:" +aplayer.getmana ());
}
}

20 of 23 Design Patterns in Java-memo mode (memento pattern)

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.