我正在从事自动售货机项目,我试图将其拆分为UI和BL层,但是我遇到了问题。例如,我有这个用于硬币支付的功能,它来自一个抽象类:
public override void Pay(decimal amount)
{
while (currentCoins < amount)
{
// Print instructions
// Get input
if (Valid)
{
// logic
}
else
{
// Print error
}
}
}
所以问题是我无法访问BL内部的UI,但是我需要与UI进行持续通信。我曾考虑过要为用户界面中的每种付款方式创建功能,但它违反了OCP ...
我正在寻找一种不会破坏SOLID原则的优雅解决方案。
是否有任何设计模式或可以解决我问题的方法? (策略模式?)我将不胜感激任何指导/想法。
谢谢:)
您可以使用观察者模式
using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using System.Collections.Concurrent;
public class program
{
public static void Main()
{
var robot = new Robot();
robot.Died += (sender, eventArgs) => Console.WriteLine("Robot Died");
robot.TakeDamage();
robot.TakeDamage();
}
}
// --- Everything above this line would be in the UI layer
// --- Everything below this line would be in the business/domain layer
public class Robot
{
private int _health = 2;
public EventHandler Died;
public Robot(){}
public void TakeDamage()
{
_health--;
if (_health == 0)
Died.Invoke(this, new EventArgs());
}
}
您必须为统一的分层体系结构创建至少3层。区分业务和数据通信非常重要。例如,如果有必要创建一个结构;
所以您的结构应该是这样;
/连接
/ entities
/ DLL
/ iDLL(接口/抽象类)
/ BLL
/ iBLL(接口/抽象类)
/ UI
您应该在iDLL中定义用于数据通信的功能。例如保存或计算或付款等。然后将这些功能实现为DLL。之后,BLL类应扩展为DLL类。在BLL中,您可以创建程序逻辑。检查直到当前的钱等于费用,如果相等,则将其发送到数据层。在执行此操作时,您可以将硬币保存在sturctur中,然后从表示层进行调用,或者可以设置反向逻辑,在表示层中进行检查,然后在业务层中进行验证。我认为第二逻辑是最好的。几乎所有的Web项目都是这样运行的。