Skip to content

Instantly share code, notes, and snippets.

// Step 4
export class GDIBrush implements PointRenderer {
colorId: number;
public draw(renderingRoots: Point[], colors: ColorMatrix, selection: Point[]): void {
const renderer = new Renderer(this, renderingRoots, colors, selection);
renderer.draw(); // !!! -> we call the method object
}
drawPoint(x: number, y: number, color: Color): void {
// Step 3
// !!! -> extracted interface with the things the
// object method uses from the original class
export interface PointRenderer {
readonly colorId: number;
drawPoint(x: number, y: number, color: Color): void;
}
// !!! -> the original class implements it
// Step 2
export class Renderer {
private readonly brush: GDIBrush;
private readonly renderingRoots: Point[];
private readonly colors: ColorMatrix;
private readonly selection: Point[];
constructor(
brush: GDIBrush,
// Step 1
export class GDIBrush {
private colorId: number;
// A long method
public draw(renderingRoots: Point[], colors: ColorMatrix, selection: Point[]): void {
// !!! -> we wrote this line and used the IDE to generate the new class
new Renderer(this, renderingRoots, colors, selection);
// some more code in the method
export class GDIBrush {
private colorId: number;
// A long method
public draw(renderingRoots: Point[], colors: ColorMatrix, selection: Point[]): void {
// some more code in the method
for (const point of renderingRoots) {
// a lot more code in the loop
this.drawPoint(point.x, point.y, colors.getColor(this.colorId));
}
export class RSCWorkflow {
private static MAX_LENGTH: number = 200;
//... more code
public validate(packet: Packet): void {
if (packet.getOriginator() === "MIA"
|| packet.getLength() > RSCWorkflow.MAX_LENGTH
|| !packet.hasValidCheckSum()) {
throw new InvalidFlowException();
@trikitrok
trikitrok / IntroduceInstanceDelegator2.ts
Created March 21, 2025 18:41
Alternative using Parameterize Constructor
// Alternative using Parameterize Constructor
export class User {
private readonly id: number;
private readonly bankingServices: BankingServices;
//!! We used Parameterize Constructor to inject a BankingServices instance to User
constructor(id: number, bankingServices: BankingServices) {
this.id = id;
this.bankingServices = bankingServices;
@trikitrok
trikitrok / IntroduceInstanceDelegator1.ts
Created March 21, 2025 18:38
Alternative using Parameterize Method
// Alternative using Parameterize Method
export class User {
private id: number;
constructor(id: number) {
this.id = id;
}
// more code...
// a utility class :(
export class BankingServices {
public static updateAccountBalance(userId: number, amount: Money): void {
// some code to update the account balance
}
// more methods...
}
export class User {
export class MessageRouter {
public route(message: Message): void {
//!! ouch... x(
ExternalRouter.getInstance().sendMessage(message);
}
}
export class ExternalRouter {
private static instance: ExternalRouter | null = null;