我是设计模式的初学者.
假设我正在开发一个C#应用程序来跟踪开发团队中各个成员(即项目跟踪器)执行的开发工作.
我试图受到战略模式的启发.
所以我正在设计我的类和接口,如下所示:
interface IEmployee
{
void Retires();
void TakesLeave();
}
interface IResponsible
{
void AcknowledgeJobAccomplish();
void CompletesJob();
}
interface ILeader
{
void FormsTeam();
void RecruitsNewMember();
void KicksOutMemberFromTheTeam();
void AssignsJob();
void UnassignsJob();
void QueriesTheJobStatus();
void ChangesTheJobStatus();
}
interface IPersistent
{
void Save();
void Update();
void Delete();
}
abstract class TeamMember : IEmployee, IResponsible, IPersistent
{
string Name;
}
class Programmer : TeamMember
{
}
class LeadProgrammer : Programmer, ILeader
{
ProgrammerCollection associateProgrammers;
}
class ProjectManager : TeamMember, ILeader
{ …Run Code Online (Sandbox Code Playgroud) 我有几个实现策略模式的Java类.每个类都有不同类型的可变数字参数:
interface Strategy {
public data execute(data);
}
class StrategyA implements Strategy {
public data execute(data);
}
class StrategyB implements Strategy {
public StrategyB(int paramA, int paramB);
public data execute(data);
}
class StrategyC implements Strategy {
public StrategyC(int paramA, String paramB, double paramC);
public data execute(data);
}
Run Code Online (Sandbox Code Playgroud)
现在我希望用户可以在某种UI中输入参数.应该在运行时选择UI,即策略应该独立于它.参数对话框不应该是单片的,并且应该有可能使它的行为和每个策略和UI看起来不同(例如控制台或Swing).
你会如何解决这个问题?
java oop model-view-controller design-patterns strategy-pattern
我想创建一个可以使用四种算法之一的类(并且使用的算法仅在运行时才知道).我认为策略设计模式听起来合适,但我的问题是每个算法需要稍微不同的参数.使用策略是一个糟糕的设计,但是将相关参数传递给构造函数?
这是一个例子(为简单起见,假设只有两种可能的算法)......
class Foo
{
private:
// At run-time the correct algorithm is used, e.g. a = new Algorithm1(1);
AlgorithmInterface* a;
};
class AlgorithmInterface
{
public:
virtual void DoSomething() = 0;
};
class Algorithm1 : public AlgorithmInterface
{
public:
Algorithm1( int i ) : value(i) {}
virtual void DoSomething(){ // Does something with int value };
int value;
};
class Algorithm2 : public AlgorithmInterface
{
public:
Algorithm2( bool b ) : value(b) {}
virtual void DoSomething(){ // Do something with …Run Code Online (Sandbox Code Playgroud) c++ inheritance design-patterns strategy-pattern code-design
这是一个关于最佳实践/设计模式的问题,而不是正则表达式.
简而言之,我有3个值:from,to和我想要改变的值.从必须匹配几种模式之一:
XX.X
>XX.X
>=XX.X
<XX.X
<=XX.X
XX.X-XX.X
Run Code Online (Sandbox Code Playgroud)
而To必须是十进制数.根据From中给出的值,我必须检查我想要更改的值是否满足From条件.例如,用户输入"From:> 100.00 To:150.00"表示应更改大于100.00的每个值.
正则表达式本身不是问题.问题是,如果我匹配整个From与一个正则表达式并且它通过我仍然需要检查输入了哪个选项 - 这将在我的代码中生成至少5个IF,并且每次我想要添加另一个选项时我将需要添加另一个如果 - 不酷.如果我要创建5个模式,同样的事情.
现在我有一个HashMap,它将一个模式作为键,一个ValueMatcher作为值.当用户输入From值然后我在循环中将其与该映射中的每个键匹配,如果匹配,那么我使用相应的ValueMatcher来实际检查我想要更改的值是否满足"From"值.
另一方面,这种方法要求我拥有一个具有所有可能性的HashMap,一个ValueMatcher接口和5个实现,每个实现只有一个简短的"匹配"方法.我认为它肯定比IF好,但看起来仍然是一个夸张的解决方案.
还有其他办法吗?或者这是我应该如何做到的?我真的很遗憾我们不能在HashMap中保存方法/将它们作为参数传递,因为那时我只有一个包含所有匹配方法的类并将它们存储在HashMap中.
如何在不使用C#中的switch或if语句的情况下处理枚举?
例如
enum Pricemethod
{
Max,
Min,
Average
}
Run Code Online (Sandbox Code Playgroud)
......我有一篇文章
public class Article
{
private List<Double> _pricehistorie;
public List<Double> Pricehistorie
{
get { return _pricehistorie; }
set { _pricehistorie = value; }
}
public Pricemethod Pricemethod { get; set; }
public double Price
{
get {
switch (Pricemethod)
{
case Pricemethod.Average: return Average();
case Pricemethod.Max: return Max();
case Pricemethod.Min: return Min();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想避免使用switch语句并使其成为通用语句.
对于特定的Pricemethod,请调用特定的计算并将其返回.
get { return CalculatedPrice(Pricemethod); }
Run Code Online (Sandbox Code Playgroud)
这里使用的模式可能有人有一个很好的实现想法.已经搜索了状态模式,但我不认为这是正确的.
以下示例无耻地从java.dzone.com中删除,并根据我的需要进行了修改:
我们的界面:
public interface CompressionStrategy
{
public void compressFiles(ArrayList<File> files);
}
Run Code Online (Sandbox Code Playgroud)
我们的第一次实施
public class GZipCompressionStrategy implements CompressionStrategy
{
public File compressFiles(ArrayList<File> files)
{
//using GZIP approach
return archive;
}
}
Run Code Online (Sandbox Code Playgroud)
第二次实施:
public class TarCompressionStrategy implements CompressionStrategy
{
public File compressFiles(ArrayList<File> files)
{
//using TAR approach
return archive;
}
}
Run Code Online (Sandbox Code Playgroud)
这是给出的用途:
public class CompressionContext
{
private CompressionStrategy strategy;
//this can be set at runtime by the application preferences
public void setCompressionStrategy(CompressionStrategy strategy)
{
this.strategy = strategy;
}
//use the …Run Code Online (Sandbox Code Playgroud) 我想创建一个使用类似于此的策略设计模式的类:
class C:
@staticmethod
def default_concrete_strategy():
print("default")
@staticmethod
def other_concrete_strategy():
print("other")
def __init__(self, strategy=C.default_concrete_strategy):
self.strategy = strategy
def execute(self):
self.strategy()
Run Code Online (Sandbox Code Playgroud)
这给出了错误:
NameError: name 'C' is not defined
Run Code Online (Sandbox Code Playgroud)
替换strategy=C.default_concrete_strategy为strategy=default_concrete_strategy将工作但是,默认情况下,策略实例变量将是静态方法对象而不是可调用方法.
TypeError: 'staticmethod' object is not callable
Run Code Online (Sandbox Code Playgroud)
如果我删除@staticmethod装饰器它会工作,但还有其他方法吗?我希望自己记录默认参数,以便其他人立即看到如何包含策略的示例.
此外,是否有更好的方法来公开策略而不是静态方法?我不认为实现完整的课程在这里有意义.
python static-methods strategy-pattern default-parameters python-3.x
在TokenRepository你可以看到3种类似的方法.它创建了令牌表的新条目,但每个方法都有不同的字段.
我怎么能重构这个?我应该将3种方法合并为1种方法还是应该使用策略模式?
TokenRepository类:
class TokenRepository
{
public function createTokenDigitalOcean(User $user, $name, $accessToken, $refreshToken = null)
{
return $user->tokens()->create([
'name' => $name,
'provider' => 'digital_ocean',
'access_token' => $accessToken,
'refresh_token' => $refreshToken,
]);
}
public function createTokenLinode(User $user, $name, $key)
{
return $user->tokens()->create([
'name' => $name,
'provider' => 'linode',
'linode_key' => $key,
]);
}
public function createTokenAws(User $user, $name, $key, $secret)
{
return $user->tokens()->create([
'name' => $name,
'provider' => 'aws',
'aws_key' => $key,
'aws_secret' => $secret,
]);
}
}
Run Code Online (Sandbox Code Playgroud)
我有3个类 …
我有一个库(加载项),其中包含一些在小型应用程序中使用的类.我想为Save该类提供一个方法,这取决于正在运行的应用程序.
为了解决这个问题,我试图使用策略模式(我可能会误解模式),但我对这个主题的理解是缺乏的.在运行时,我提供了一个处理保存的策略类.公共类公开一种Save方法,将其中继到提供的策略类.但为了保持一致性,我认为普通类也必须实现策略接口.
IRecord(通用类)接口:
Public Function DoSomething(): End Function
Public Function SetStrategy(ByVal Strategy As IDatabaseStrategy): End Function
Run Code Online (Sandbox Code Playgroud)
记录(公共类)实施:
Private RecordStrategy As IDatabaseStrategy
Implements IRecord
Implements IDatabaseStrategy 'Implements this interface to have Save method
Private Function IRecord_DoSomething():
'does whatever the class is supposed to do
End Function
Private Function IRecord_SetStrategy(ByVal Strategy As IDatabaseStrategy)
Set RecordStrategy = Strategy
End Function
Private Function IDataBaseStrategy_Save()
RecordStrategy.Save
End Function
Run Code Online (Sandbox Code Playgroud)
战略接口和实施:
IDatabaseStrategy: Public Function Save():End Function
DataBaseStrategyA:
Implements IDatabaseStrategy
Private Function IDataBaseStrategy_Save()
Debug.Print …Run Code Online (Sandbox Code Playgroud)我觉得我像标题一样玩了流行语宾果游戏。这是我要问的一个简洁示例。假设我对某些实体有一些继承层次结构。
class BaseEntity { ... }
class ChildAEntity : BaseEntity { ... }
class GrandChildAEntity : ChildAEntity { ... }
class ChildBEntity : BaseEntity { ... }
Run Code Online (Sandbox Code Playgroud)
现在让我们说说我为服务提供了一个通用接口,该接口具有使用基类的方法:
interface IEntityService<T> where T : BaseEntity { void DoSomething(BaseEntity entity)... }
Run Code Online (Sandbox Code Playgroud)
我有一些具体的实现:
class BaseEntityService : IEntityService<BaseEntity> { ... }
class GrandChildAEntityService : IEntityService<GrandChildAEntity> { ... }
class ChildBEntityService : IEntityService<ChildBEntity> { ... }
Run Code Online (Sandbox Code Playgroud)
假设我已经将所有这些都注册到了容器中。所以,现在我的问题是,如果我迭代通过List的BaseEntity?我如何获得注册的服务与最接近的匹配?
var entities = List<BaseEntity>();
// ...
foreach(var entity in entities)
{
// Get the …Run Code Online (Sandbox Code Playgroud) c# generics dependency-injection strategy-pattern decorator-pattern
strategy-pattern ×10
java ×3
c# ×2
c++ ×1
code-design ×1
enums ×1
excel ×1
generics ×1
inheritance ×1
laravel ×1
laravel-5 ×1
oop ×1
php ×1
polymorphism ×1
python ×1
python-3.x ×1
vba ×1