gpt4 book ai didi

c# - OOP 实现问题

转载 作者:行者123 更新时间:2023-11-30 17:42:17 25 4
gpt4 key购买 nike

项目的思路是html渲染器。但是我想通过使用 Strategy 设计模式(不确定它的策略 :D)使它更有活力。

渲染策略:

public abstract class RenderStrategy
{
private Element _RenderElement;
public RenderStrategy(Element renderElement)
{
this._RenderElement = renderElement;
}
public abstract String Render();
}

元素:

public abstract class Element
{

public String Render(RenderStrategy strategy)
{
return strategy.Render();
}
}

enter image description here

我的问题是 CompositeElement 在不需要渲染复合元素策略

最佳答案

我会这样做:

public interface IStrategy 
{
string Render();
}

public class Element : IStrategy
{
public string Render() {
return "rendering for element";
}
}

public class CompositeElement : IStrategy
{
public string Render() {
return "rendering for composite element";
}
}
public class HTMLRenderer
{
private ISTrategy ele = new Element();
private IStrategy comp = new CompositeElement();
private IStrategy curr;
public HTMLREnderer(){
curr = ele; //i set default here to Element, but you can change it base on your need
}
public void RenderNow(){
Console.WriteLine(curr.Render());
//change your strategy accordingly to your need here, may be?
}
}

关于c# - OOP 实现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32077211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com