Created
December 13, 2023 21:15
-
-
Save codejockie/53212f3d3b618a52f53f155ea2033dd6 to your computer and use it in GitHub Desktop.
Design Patterns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var hole = new RoundHole(5); | |
var rPeg = new RoundPeg(5); | |
hole.Fits(rPeg).Dump(); // True | |
var sm_sqpeg = new SquarePeg(5); | |
var lg_sqpeg = new SquarePeg(10); | |
//hole.Fits(sm_sqpeg); // Error: won't compile (incompatible types) | |
var sm_sqpeg_adapter = new SquarePegAdapter(sm_sqpeg); | |
var lg_sqpeg_adapter = new SquarePegAdapter(lg_sqpeg); | |
hole.Fits(sm_sqpeg_adapter).Dump(); // True | |
hole.Fits(lg_sqpeg_adapter).Dump(); // False | |
class RoundHole | |
{ | |
public double Radius { get; private set; } | |
public RoundHole(double radius) | |
{ | |
Radius = radius; | |
} | |
public bool Fits(RoundPeg peg) | |
{ | |
return Radius >= peg.Radius; | |
} | |
} | |
class RoundPeg | |
{ | |
public double Radius { get; private set; } | |
public RoundPeg(double radius) | |
{ | |
Radius = radius; | |
} | |
} | |
class SquarePeg | |
{ | |
public double Width { get; private set; } | |
public SquarePeg(double width) | |
{ | |
Width = width; | |
} | |
} | |
class SquarePegAdapter : RoundPeg | |
{ | |
private readonly SquarePeg Peg; | |
public SquarePegAdapter(SquarePeg peg) : base(peg.Width * Math.Sqrt(2) / 2) | |
{ | |
Peg = peg; | |
} | |
public new double Radius => Peg.Width * Math.Sqrt(2) / 2; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment