我有一段代码(一个外观),它在aws上创建每个基础结构组件。
private void synthesizeStack() {
Deployer<Vpc> vpcDeployer = new VpcDeployer(this);
Deployer<Bucket> s3Deployer = new S3Deployer(this);
Vpc vpc = vpcDeployer.deploy();
Bucket bucket = s3Deployer.deploy();
Deployer<SecurityGroup> bastionSecurityGroupDeployer = new BastionSecurityGroupDeployer(this, vpc);
SecurityGroup bastionSecurityGroup = bastionSecurityGroupDeployer.deploy();
Deployer<Instance> bastionDeployer = new BastionDeployer(this, vpc, bastionSecurityGroup);
Deployer<SecurityGroup> rdsSecurityGroupDeployer = new RdsSecurityGroupDeployer(this, vpc, bastionSecurityGroup);
SecurityGroup rdsSecurityGroup = rdsSecurityGroupDeployer.deploy();
Deployer<DatabaseCluster> rdsDeployer = new RdsDeployer(this, vpc, rdsSecurityGroup);
Deployer<List<Lambda>> lambdaDeployer = new LambdaDeployer(this, bucket);
rdsDeployer.deploy();
bastionDeployer.deploy();
lambdaDeployer.deploy();
}我试图给所有部署人员一个通用接口,但是每个部署程序都有不同的参数和返回类型,所以我创建了一个通用接口。
我如何简化这段代码?有更好的办法吗?
发布于 2020-02-05 16:55:18
真的,你只是在根据你的个人喜好重新整理代码。您可以有各种安排,例如:
就我个人而言,我不喜欢Deployer(object).Deploy(),因为它留下了一个无用的Deployer对象。
Object.Deploy()适用于对象挂起并对其执行多项操作的事情,但在您的情况下,我认为它更像一个数据对象,您并不想将部署代码作为其职责的一部分。
Deployer.Deploy(object)将是我的最爱。您可能会将一些东西部署到一个AWS帐户中,这样您就可以将Deployer保持在周围并传递它的对象。
现在,您有一个问题,您可能需要部署程序上的多个方法。
我不认为这一定是坏事。但是,您可以使用泛型方法稍微减轻它。
public class S3
{
public string DeploymentInstructions { get; set; }
public string DeployedObject { get; set; }
}
public interface IDeployer
{
T Deploy<T>(T data);
}
public class S3Deployer : IDeployer
{
public T Deploy<T>(T data)
{
if(data is S3)
{
//deploy
Console.WriteLine($"deploying s3 {(data as S3).DeploymentInstructions}");
(data as S3).DeployedObject = "result of deployment";
return data;
}
else
{
throw new Exception("type not supported");
}
}
}
public class GeneralDeployer : IDeployer
{
private Dictionary<Type, IDeployer> concreteDeployers;
public GeneralDeployer()
{
concreteDeployers = new Dictionary<Type, IDeployer>();
concreteDeployers.Add(typeof(S3), new S3Deployer());
}
public T Deploy<T>(T data)
{
if(concreteDeployers.ContainsKey(typeof(T)))
{
return concreteDeployers[typeof(T)].Deploy(data);
}
return default(T);
}
}https://softwareengineering.stackexchange.com/questions/404735
复制相似问题