jeudi 28 janvier 2016

How to explain design pattern of singleton with python?

I think use polygamy example is good to explain how this work does.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Phil Huang <pichuang@cs.nctu.edu.tw>

# pylint: disable=missing-docstring, line-too-long, too-few-public-methods

"""
Singleton

Reference
http://ift.tt/1kaspPp
http://ift.tt/1KCunDn
http://ift.tt/1ROVe53
"""


class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]


class Husband(metaclass=Singleton):
    def __init__(self):
        self.name = "pichuang"


class Wife(object):
    def __init__(self, name, husband):
        self.name = name
        self.husband = husband

    def love(self):
        print("{0} love {1} (object id is {2})".format(self.name, 

self.husband.name, id(self.husband)))

def main():
    wife_1 = Wife(name="Arimura Kasumi", husband=Husband())  # http://ift.tt/1QuLQ3A
    wife_2 = Wife(name="Hashimoto Kanna", husband=Husband())  # http://ift.tt/1ROVbq3
    wife_1.love()
    wife_2.love()


if __name__ == '__main__':
    main()

We can know polygamy is one husband, one or more wife. So, we just create one husband instance with Husband class and create one or more wifi instance with Wifi class.

In this case, Arimura Kasumi and Hashimoto Kanna are two of wifi instances, and "pichuang" is one of husband instance. They only love their husband, and the answer is one.

Source code: pichuang/Design Pattern of Loser

Aucun commentaire:

Enregistrer un commentaire