CSharp · Console
using System;
public class Program
{
public static void Main()
{
var theThingTrue = new BuilderFoo().BuildFooTrue()
.WithSomePropertyOnlyForTrue("face").Build();
//var theThingTrueCompilerError = new BuilderFoo().BuildFooTrue().WithB(5).Build(); // compiler error
var theThingFalse = new BuilderFoo().BuildFooFalse()
.WithB(5).Build();
//var theThingFalseCompilerError = new BuilderFoo().BuildFooFalse().WithSomePropertyOnlyForTrue("face").Build(); // compiler error
Console.WriteLine("hello");
}
}
public interface ISettings
{
string SomePropertyOnlyForTrue { get; }
int B { get; }
}
public class Settings : ISettings
{
public string SomePropertyOnlyForTrue { get; }
public int B { get; }
public Settings(string somePropertyOnlyForTrue)
{
SomePropertyOnlyForTrue = somePropertyOnlyForTrue;
}
public Settings(int b)
{
B = b;
}
}
public interface IBuilderFoo
{
IBuilderFooTrue BuildFooTrue();
IBuilderFooFalse BuildFooFalse();
}
public class BuilderFoo : IBuilderFoo
{
public IBuilderFooTrue BuildFooTrue()
{
return new BuilderFooTrue();
}
public IBuilderFooFalse BuildFooFalse()
{
return new BuilderFooFalse();
}
}
public interface IBuilderFooTrue
{
IBuilderFooTrue WithSomePropertyOnlyForTrue(string value);
ISettings Build();
}
public class BuilderFooTrue : IBuilderFooTrue
{
private string _somePropertyOnlyForTrue = string.Empty;
public IBuilderFooTrue WithSomePropertyOnlyForTrue(string value)
{
_somePropertyOnlyForTrue = value;
return this;
}
public ISettings Build()
{
return new Settings(_somePropertyOnlyForTrue);
}
}
public interface IBuilderFooFalse
{
IBuilderFooFalse WithB(int value);
ISettings Build();
}
public class BuilderFooFalse : IBuilderFooFalse
{
private int _b;
public IBuilderFooFalse WithB(int value)
{
_b = value;
return this;
}
public ISettings Build()
{
return new Settings(_b);
}
}