Design Pattern-Python version (6)-prototype Pattern

Source: Internet
Author: User

Prototype:

Application features: it is used when a large number of modifications are required based on a basic prototype to obtain a new prototype.

Structure Features: Object replication mechanism [light replication and deep replication]

UML:

#!/usr/bin/env python  #encoding: utf-8  from copy import copy, deepcopyclass test_obj:    def __init__(self, id):        self.id = id    class proto_type:    def __init__(self, name, id):        self.name = name        self.obj = test_obj(id)        def display(self):        print self.name        print self.obj.id    def clone(self):        return copy(self)        def deep_clone(self):        return deepcopy(self)          if '__main__' == __name__:      obj1 = proto_type('name1', 1)    obj2 = obj1.clone()    obj3 = obj1.deep_clone()    obj2.name = 'name2'    obj2.obj.id = 2    obj3.name = 'name3'    obj3.obj.id = 3     obj1.display()    obj2.display()    obj3.display()    print obj1.__class__    print obj2.__class__    print obj3.__class__  

Result:

Name12 # Because obj2 is a light copy, the object is not copied. As a result, modifications to the new object affect the original object Value name22name33 # because it is a deep copy, so it will not affect the old object _ main __. proto_type _ main __. proto_type _ main __. proto_type

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.