python设计模式——抽象工厂

from abc import ABC, abstractmethod
from typing import Type, Union, Optional
import random


class Phone(ABC):
    def __init__(self, model: str) -> None:
        self.model = model

    @abstractmethod
    def call(self) -> None:
        ...

    def __str__(self) -> str:
        return self.model


class OnePlus(Phone):
    def call(self) -> None:
        print(f"我用 {self} 给你打电话")

    def __str__(self) -> str:
        return f"一加 {self.model}"


class HuaWei(Phone):
    def call(self) -> None:
        print(f"我用 {self} 给你打电话")

    def __str__(self) -> str:
        return f"华为 {self.model}"


class PhoneShop:
    def __init__(self, phone_shop: Type[Phone]) -> None:
        self.phone_shop = phone_shop

    def buy_phone(self, phone_model: str) -> Phone:
        return self.phone_shop(phone_model)


def random_phone() -> Union[OnePlus, HuaWei]:
    """
    获取随机手机
    :return: 
    """
    _random_data = {
        OnePlus: ["5T", "7"],
        HuaWei: ["Magic 2", "Magic 1"]
    }
    _random_shop = random.choice(list(_random_data.keys()))

    return _random_shop(random.choice(_random_data[_random_shop]))


def random_phone_shop(name: Optional[str] = None) -> Type[Phone]:
    """
    如果有name 则获取对应name的手机商店,否则获取随机的手机商店
    :param name: 
    :return: 
    """
    option = {"HuaWei": HuaWei, "OnePlus": OnePlus}
    if name and name in option.keys():
        return option[name]
    return random.choice([HuaWei, OnePlus])


if __name__ == '__main__':
    phone_shop_1 = PhoneShop(HuaWei)
    phone_models_1 = ["Magic 1", "Magic 2"]
    for _ in phone_models_1:
        phone_1 = phone_shop_1.buy_phone(_)
        phone_1.call()

    phone_shop_2 = PhoneShop(OnePlus)
    phone_models_2 = ["5T", "7"]
    for _ in phone_models_2:
        phone_2 = phone_shop_2.buy_phone(_)
        phone_2.call()

    my_phone = random_phone_shop()
    if my_phone == HuaWei:
        my_phone = my_phone(random.choice(["Magic 2", "Magic 1"]))
        my_phone.call()
    if my_phone == OnePlus:
        my_phone = my_phone(random.choice(["5T", "7"]))
        my_phone.call()

from abc import ABC, abstractmethod
import json
from typing import Type


class User:
    def __init__(self, username: str, age: int) -> None:
        self.username = username
        self.age = age

    def __str__(self) -> str:
        return f"用户名: {self.username}, 年龄: {self.age}"


class DataBaseConnection(ABC):
    def __init__(self, config: str) -> None:
        self.config = json.loads(config)
        print(self.config)

    @abstractmethod
    def insert_user(self, user_data: User) -> None:
        ...

    @abstractmethod
    def delete_user(self, user_data: User) -> None:
        ...


class MysqlConnection(DataBaseConnection):
    def insert_user(self, user_data: User) -> None:
        print(f"INSERT INTO user ( username, age ) VALUES( '{user_data.username}', {user_data.age});")

    def delete_user(self, user_data: User) -> None:
        print(f"DELETE FROM user WHERE user.username = '{user_data.username}';")


class MongoConnection(DataBaseConnection):
    def insert_user(self, user_data: User) -> None:
        print(f"db.user.insert({{username: '{user_data.username}', age: '{user_data.age}' }})")

    def delete_user(self, user_data: User) -> None:
        print(f"db.user.remove({{username: '{user_data.username}' }})")


class DataBaseConnectionFactory:
    _connect = {
        'mysql': MysqlConnection,
        'mongo': MongoConnection
    }
    _default = MysqlConnection

    def __init__(self, connect_type: str) -> None:
        self.connect_type = connect_type

    def get_connection(self) -> Type[DataBaseConnection]:
        if self.connect_type in self._connect.keys():
            return self._connect[self.connect_type]
        return self._default


if __name__ == '__main__':
    user = User("lllyyb", 18)
    mysql_connection = MysqlConnection('{"host": "localhost", "user": "root", "password": "password", "port": 3306}')
    mysql_connection.insert_user(user)
    mysql_connection.delete_user(user)
    mongo_connection = MongoConnection('{"host": "localhost", "user": "root", "password": "password", "port": 27017}')
    mongo_connection.insert_user(user)
    mongo_connection.delete_user(user)
    print("==================")
    config_from_config_file = {'type': 'mysql',
                               'config': '{"host": "localhost", "user": "root", "password": "password", "port": 3306}'}
    get_form_config = DataBaseConnectionFactory(config_from_config_file['type'])
    connection = get_form_config.get_connection()(config_from_config_file['config'])
    connection.insert_user(user)
    connection.delete_user(user)


补充

ABC 用于定义抽象基类,无法被实例化。
abstractmethod 抽象方法,继承的子类没有实现抽象方法的话,实例化会报错。


右下角对话与我联系。


评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×