我正在尝试通过在Python中实现MVP来理解它。我通过以下链接在Java中翻译了示例:https://www.dreamincode.net/forums/topic/353210-swing-passive-model-view-presenter-in-5-minutes/
此程序检查密码是否正确。该模型从数据库获取密码(在本例中为简单的字符串,称为密码)。
我不确定主要方法。我的代码是面向桌面的,而不是基于Web的,因此,据我所知,视图应该优先。我想知道流程是否正确。我很难过,主要是因为View调用了Presenter,Presenter也调用了View,所以哪个先出现,谁初始化谁?
在原始文章中,方法View.createUI()在View构造函数(初始化程序)中初始化。我必须在main()中最后调用它,因为在视图内部还没有初始化Presenter类,所以self.Presenter.login(passwd)还不存在。
谢谢
./main.py
import modules
def main():
View = modules.View()
Model = modules.Model()
Presenter = modules.Presenter(View, Model)
View.setPresenter(Presenter)
View.createUI()
if __name__ == "__main__":
main()
./models/Model.py
class Model:
def __init__(self):
self.password = "password"
def setPassword(self, password):
self.password = password
def getPassword(self):
return self.password
./models/View.py
class View:
def __init__(self ):
self.Presenter = None
#self.createUI()
def createUI(self):
passwd = "password"
self.Presenter.login(passwd)
def setPresenter(self, Presenter):
self.Presenter = Presenter
def updateStatusLabel(self, text):
print(text)
./models/Presenter.py
class Presenter:
def __init__(self, View, Model):
self.View = View
self.Model = Model
def login(self, password):
result = "incorrect password"
if self.Model.getPassword() == password:
result = "Correct password"
self.View.updateStatusLabel(result)
./models/__init__.py
from modules.Model import Model
from modules.View import View
from modules.Presenter import Presenter