简体   繁体   中英

How to implement Strategy Pattern with Base class dependencies?

I'm looking to implement the Strategy Pattern and was on my way to do as the answer in Stack Strat Pattern . But realised that I would be unable to copy it right of the bat. What I want to do is implement the pattern but also make sure that my executeReplacement functions inherit from the base class.

class DB():

    def __init__(self, league, season, func=None):
        self.db_user = os.environ.get('DB_user')
        self.db_pass = os.environ.get('DB_pass')
        self.MONGODB_URL = f'mongodb+srv://{db_user}:{db_pass}@database-mbqxj.mongodb.net/test?retryWrites=true&w=majority'
        self.client = MongoClient(MONGODB_URL)
        self.DATABASE = client["Database"]
        self.league = league
        self.season = season
        self.pool = multiprocessing.cpu_count()
        if func:
            self.execute = func

        def execute(self):
            print("No execution specified")

def executeReplacement1():
    """Should inherit the the properties of the base class
    since it's dependant on it's properties (Connect to Database etc.)"""
    print("Push some data to DATABASE")


def executeReplacement2():
    """Should inherit the the properties of the base class
    since it's dependant on it's properties (Connect to Database etc.)"""
    print("Push some other data to DATABASE")

How would one build the Strategy Pattern so that the replacement functions inherit the properties of the base class? Or is this perhaps not the optimal approach?

The goal is to parse arguments from stdin like:

`db --push EN_PR 2019 player``

Which will create an instance of the class DB in where the methods are bound to push where push is a functions that uploads data to the database.

The function should be defined to take a DB instance as an argument, then DB.execute can pass self when calling it.

class DB():

    def __init__(self, league, season, func=None):
        self.db_user = os.environ.get('DB_user')
        self.db_pass = os.environ.get('DB_pass')
        self.MONGODB_URL = f'mongodb+srv://{db_user}:{db_pass}@database-mbqxj.mongodb.net/test?retryWrites=true&w=majority'
        self.client = MongoClient(MONGODB_URL)
        self.DATABASE = client["Database"]
        self.league = league
        self.season = season
        self.pool = multiprocessing.cpu_count()
        

        def execute(self):
            

def executeReplacement1():
    print("Push some data to DATABASE")


def executeReplacement2():
    print("Push some other data to DATABASE")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM