スタック オーバーフローに関するこの特定の質問に対する回答が見つからなかったので、ここに投稿します。
必要なデータベースに応じて、抽象クラスからデータベース処理オブジェクトを生成するファクトリ クラスがあります (コードを参照)。
私の質問はこれです。データベースハンドラーにのみ適用できる一般的なメソッドがいくつかあります...そのため、それらを独自のモジュールに配置するのは適切ではないと思います...しかし、それらを配置する適切な場所がどこにあるかわかりません。
それらを抽象クラスに入れることは確かに機能しますが、それが受け入れられる場所かどうかはわかりません。
抽象クラス
class DBHandlerAbstract(object): # ABSTRACT CLASS ---
__metaclass__ = abc.ABCMeta
# I HAVE TO BE OVERRIDDEN
@abc.abstractmethod
def open(self):
raise NotImplementedError
# I HAVE TO BE OVERRIDDEN
@abc.abstractmethod
def close(self):
raise NotImplementedError
# SHOULD THIS GF GO HERE OR ELSEWHERE???
def _check_host(self):
print 'this will be the same for all dbhandler objects'
ファクトリークラス
class DBHandler(object): # FACTORY CLASS ---
"""
This is a factory class that will call and return a subclass.
It is NOT an abstract class.
The objects classes that are instantiated by this factory will be
subclasses of DBHandler
"""
@staticmethod
def handler(service, *args, **kwargs):
# Microsoft SQL (mssql)
if re.match("^(\s*)ms(\s*)sql.*$", str(service.lower())):
return DBHandler_MSSQL(*args, **kwargs)
# MySQL
elif re.match("^(\s*)my(\s*)sql.*$", str(service.lower())):
return DBHandler_MYSQL(*args, **kwargs)
else:
log.error(MSG.DBHandlerNotProvided())
raise TypeError('DBHandler service not provided.')
機能クラス
class DBHandler_MSSQL(DBHandlerAbstract): # FUNCTIONAL CLASS ---
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
self._check_host()
...stuff and things...
gethandler.py
class test(object):
def __init__(self):
app_name = 'dbhandler_test'
logfile = 'system'
log_level = 10
screendump = True
DBO = DBHandler.handler('mssql')
...stuff and things...