Python design mode 22nd Day "Memo mode"

Source: Internet
Author: User

1. Application Scenarios

(1) Can save the state of the object, and can revert to the previous state

2. Code implementation

#!/usr/bin/env python#! _*_ coding:utf-8 _*_classoriginator (object):" "This is the basic class" "    def __init__(self, State): Self.state= StatedefCreatememento (self):" "Create a Memo" "        returnMemento (self.state)defSetmemento (Self, memento):" "Recover from Memo" "self.state=memento.stateclassMemento (object):" "then the memo class" "    def __init__(self, State): Self.state= Stateclasscaretaker (object):" "then the memo management class" "    def __init__(self):Pass    defSetmemento (Self, memento):" "use a memo as a reference" "Self.memento=MementodefGetmemento (self):" "getting references from management" "        returnSelf.mementoif __name__=="__main__": Originator= Originator ("state1")    PrintOriginator.state Memento=Originator.creatememento () caretaker=caretaker () Caretaker.setmemento (memento) originator.state="State2"    Printoriginator.state Originator.setmemento (Caretaker.getmemento ())PrintOriginator.state

Results:

/users/liudaoqiang/pycharmprojects/numpy/venv/bin/python/users/liudaoqiang/project/python_project/day22_ memento/Memento_test.pystate1state2state1process finished with exit code 0

Python design mode 22nd Day "Memo mode"

Related Article

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.