```, where ```pattern-name``` is pattern filename in ```examples``` directory.
22 |
23 | **Examples:**
24 |
25 | Singleton:
26 |
27 | ```shell
28 | npm run singleton
29 | ```
30 |
31 | Builder:
32 |
33 | ```shell
34 | npm run builder
35 | ```
36 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/mediator/example/mediator/Note.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.mediator.example.mediator;
2 |
3 | /**
4 | * Note class.
5 | */
6 | public class Note {
7 | private String name;
8 | private String text;
9 |
10 | public Note() {
11 | name = "New note";
12 | }
13 |
14 | public void setName(String name) {
15 | this.name = name;
16 | }
17 |
18 | public void setText(String text) {
19 | this.text = text;
20 | }
21 |
22 | public String getName() {
23 | return name;
24 | }
25 |
26 | public String getText() {
27 | return text;
28 | }
29 |
30 | @Override
31 | public String toString() {
32 | return name;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/courses/guru/js/patterns/state/context.js:
--------------------------------------------------------------------------------
1 | // define interface of interest of Client
2 | // maintain reference to instance of State subclasses
3 | class Context {
4 | // reference to Context current state
5 | #state = null;
6 |
7 | constructor(state) {
8 | this.transitionTo(state);
9 | }
10 |
11 | // change State at runtime
12 | transitionTo(state) {
13 | console.log(`Context: transition to: ${state.constructor.name}`);
14 | this.#state = state;
15 | this.#state.context = this;
16 | }
17 |
18 | /* --- Context delegates part of its behavior to current State --- */
19 | request1() {
20 | this.#state.handle1();
21 | }
22 |
23 | request2() {
24 | this.#state.handle2();
25 | }
26 | }
27 |
28 | export { Context };
29 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/memento/example/shapes/Circle.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.memento.example.shapes;
2 |
3 | import java.awt.*;
4 |
5 | public class Circle extends BaseShape {
6 | private int radius;
7 |
8 | public Circle(int x, int y, int radius, Color color) {
9 | super(x, y, color);
10 | this.radius = radius;
11 | }
12 |
13 | @Override
14 | public int getWidth() {
15 | return radius * 2;
16 | }
17 |
18 | @Override
19 | public int getHeight() {
20 | return radius * 2;
21 | }
22 |
23 | @Override
24 | public void paint(Graphics graphics) {
25 | super.paint(graphics);
26 | graphics.drawOval(x, y, getWidth() - 1, getHeight() - 1);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/builder/example/components/TripComputer.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.builder.example.components;
2 |
3 | import refactoring_guru.builder.example.cars.Car;
4 |
5 | /**
6 | * Just another feature of a car.
7 | */
8 | public class TripComputer {
9 |
10 | private Car car;
11 |
12 | public void setCar(Car car) {
13 | this.car = car;
14 | }
15 |
16 | public void showFuelLevel() {
17 | System.out.println("Fuel level: " + car.getFuel());
18 | }
19 |
20 | public void showStatus() {
21 | if (this.car.getEngine().isStarted()) {
22 | System.out.println("Car is started");
23 | } else {
24 | System.out.println("Car isn't started");
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/singleton/example/non_thread_safe/Singleton.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.singleton.example.non_thread_safe;
2 |
3 | public final class Singleton {
4 | private static Singleton instance;
5 | public String value;
6 |
7 | private Singleton(String value) {
8 | // Following code emulates slow initialization.
9 | try {
10 | Thread.sleep(1000);
11 | } catch (InterruptedException ex) {
12 | ex.printStackTrace();
13 | }
14 | this.value = value;
15 | }
16 |
17 | public static Singleton getInstance(String value) {
18 | if (instance == null) {
19 | instance = new Singleton(value);
20 | }
21 | return instance;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/prototype/example/shapes/Circle.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.prototype.example.shapes;
2 |
3 | public class Circle extends Shape {
4 | public int radius;
5 |
6 | public Circle() {
7 | }
8 |
9 | public Circle(Circle target) {
10 | super(target);
11 | if (target != null) {
12 | this.radius = target.radius;
13 | }
14 | }
15 |
16 | @Override
17 | public Shape clone() {
18 | return new Circle(this);
19 | }
20 |
21 | @Override
22 | public boolean equals(Object object2) {
23 | if (!(object2 instanceof Circle) || !super.equals(object2)) return false;
24 | Circle shape2 = (Circle) object2;
25 | return shape2.radius == radius;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/courses/guru/php/src/RefactoringGuru/TemplateMethod/Structural/Output.txt:
--------------------------------------------------------------------------------
1 | Same client code can work with different subclasses:
2 | AbstractClass says: I am doing bulk of the work
3 | ConcreteClass1 says: Implemented Operation1
4 | AbstractClass says: But I let subclasses to override some operations
5 | ConcreteClass1 says: Implemented Operation2
6 | AbstractClass says: But I am doing bulk of the work anyway
7 |
8 | Same client code can work with different subclasses:
9 | AbstractClass says: I am doing bulk of the work
10 | ConcreteClass2 says: Implemented Operation1
11 | AbstractClass says: But I let subclasses to override some operations
12 | ConcreteClass2 says: Overridden Hook1
13 | ConcreteClass2 says: Implemented Operation2
14 | AbstractClass says: But I am doing bulk of the work anyway
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/adapter/example/adapters/SquarePegAdapter.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.adapter.example.adapters;
2 |
3 | import refactoring_guru.adapter.example.round.RoundPeg;
4 | import refactoring_guru.adapter.example.square.SquarePeg;
5 |
6 | /**
7 | * Adapter allows fitting square pegs into round holes.
8 | */
9 | public class SquarePegAdapter extends RoundPeg {
10 | private SquarePeg peg;
11 |
12 | public SquarePegAdapter(SquarePeg peg) {
13 | this.peg = peg;
14 | }
15 |
16 | @Override
17 | public double getRadius() {
18 | double result;
19 | // Calculate a minimum circle radius, which can fit this peg.
20 | result = (Math.sqrt(Math.pow((peg.getWidth() / 2), 2) * 2));
21 | return result;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/factory_method/example/factory/Dialog.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.factory_method.example.factory;
2 |
3 | import refactoring_guru.factory_method.example.buttons.Button;
4 |
5 | /**
6 | * Base factory class. Note that "factory" is merely a role for the class. It
7 | * should have some core business logic which needs different products to be
8 | * created.
9 | */
10 | public abstract class Dialog {
11 |
12 | public void renderWindow() {
13 | // ... other code ...
14 |
15 | Button okButton = createButton();
16 | okButton.render();
17 | }
18 |
19 | /**
20 | * Subclasses will override this method in order to create specific button
21 | * objects.
22 | */
23 | public abstract Button createButton();
24 | }
25 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/strategy/example/OutputDemo.txt:
--------------------------------------------------------------------------------
1 | Please, select a product:
2 | 1 - Mother board
3 | 2 - CPU
4 | 3 - HDD
5 | 4 - Memory
6 | 1
7 | Count: 2
8 | Do you wish to continue selecting products? Y/N: y
9 | Please, select a product:
10 | 1 - Mother board
11 | 2 - CPU
12 | 3 - HDD
13 | 4 - Memory
14 | 2
15 | Count: 1
16 | Do you wish to continue selecting products? Y/N: n
17 | Please, select a payment method:
18 | 1 - PalPay
19 | 2 - Credit Card
20 | 1
21 | Enter the user's email: user@example.com
22 | Enter the password: qwerty
23 | Wrong email or password!
24 | Enter user email: amanda@ya.com
25 | Enter password: amanda1985
26 | Data verification has been successful.
27 | Pay 6250 units or Continue shopping? P/C: p
28 | Paying 6250 using PayPal.
29 | Payment has been successful.
30 |
--------------------------------------------------------------------------------
/courses/guru/js/patterns/command/commands/complex.js:
--------------------------------------------------------------------------------
1 | // reference to some Receiver
2 | let privateReceiver = null;
3 |
4 | /* --- context data --- */
5 | let privateA = null;
6 | let privateB = null;
7 |
8 | // delegate "complex" operations to other objects: Recievers
9 | class ComplexCommand {
10 | // can accept one or several Receiver objects + some context data
11 | constructor(receiver, a, b) {
12 | privateReceiver = receiver;
13 | privateA = a;
14 | privateB = b;
15 | }
16 |
17 | // command can be delegated to any Receiver method
18 | execute() {
19 | console.log('ComplexCommand: complex command will be done by receiver object.');
20 | privateReceiver.doSmth(privateA);
21 | privateReceiver.doSmthElse(privateB);
22 | }
23 | }
24 |
25 | export { ComplexCommand };
26 |
--------------------------------------------------------------------------------
/courses/guru/php/src/RefactoringGuru/Flyweight/Structural/Output.txt:
--------------------------------------------------------------------------------
1 |
2 | FlyweightFactory: I have 5 flyweights:
3 | Chevrolet_Camaro2018_pink
4 | Mercedes Benz_C300_black
5 | Mercedes Benz_C500_red
6 | BMW_M5_red
7 | BMW_X6_white
8 |
9 | Client: Adding a car to database.
10 | FlyweightFactory: Reusing existing flyweight.
11 | Flyweight: Displaying shared (["BMW","M5","red"]) and unique (["CL234IR","James Doe"]) state.
12 |
13 | Client: Adding a car to database.
14 | FlyweightFactory: Can't find a flyweight, creating new one.
15 | Flyweight: Displaying shared (["BMW","X1","red"]) and unique (["CL234IR","James Doe"]) state.
16 |
17 | FlyweightFactory: I have 6 flyweights:
18 | Chevrolet_Camaro2018_pink
19 | Mercedes Benz_C300_black
20 | Mercedes Benz_C500_red
21 | BMW_M5_red
22 | BMW_X6_white
23 | BMW_X1_red
24 |
--------------------------------------------------------------------------------
/courses/guru/js/examples/adapter.js:
--------------------------------------------------------------------------------
1 | import { Target, Adaptee, Adapter } from '../patterns/adapter';
2 |
3 | // this function supports all classes that follows Target interface
4 | function clientCode(target) {
5 | console.log(target.request());
6 | }
7 |
8 | // call Target method
9 | console.log('Client: can work with Target objects:');
10 | const target = new Target();
11 | clientCode(target);
12 |
13 | // call incompatable with Target Adaptee's method
14 | const adaptee = new Adaptee();
15 | console.log('Client: Adaptee has incompatable interface!');
16 | console.log('ADAPTEE: %s', adaptee.incompatableRequest());
17 |
18 | // now we can call Adaptee incompatable method via Adapter
19 | console.log('Client: can work with it via Adapter:');
20 | const adapter = new Adapter(adaptee);
21 | clientCode(adapter);
22 |
--------------------------------------------------------------------------------
/courses/guru/c#/RefactoringGuru.DesignPatterns.TemplateMethod.Structural/Output.txt:
--------------------------------------------------------------------------------
1 | Same client code can work with different subclasses:
2 | AbstractClass says: I am doing the bulk of the work
3 | ConcreteClass1 says: Implemented Operation1
4 | AbstractClass says: But I let subclasses override some operations
5 | ConcreteClass1 says: Implemented Operation2
6 | AbstractClass says: But I am doing the bulk of the work anyway
7 |
8 | Same client code can work with different subclasses:
9 | AbstractClass says: I am doing the bulk of the work
10 | ConcreteClass2 says: Implemented Operation1
11 | AbstractClass says: But I let subclasses override some operations
12 | ConcreteClass2 says: Overridden Hook1
13 | ConcreteClass2 says: Implemented Operation2
14 | AbstractClass says: But I am doing the bulk of the work anyway
--------------------------------------------------------------------------------
/courses/guru/js/examples/iterator.js:
--------------------------------------------------------------------------------
1 | import { Collection1 } from '../patterns/iterator';
2 |
3 | // client code may or may not to know about concrete Iterator or Collection classes
4 |
5 | /* --- make collection and add some items --- */
6 | const collection1 = new Collection1();
7 | collection1.addItem(1);
8 | collection1.addItem(2);
9 | collection1.addItem(3);
10 |
11 | // make straight iterator
12 | const iterator1 = collection1.getIterator();
13 |
14 | console.log('Straight traversal:');
15 | while (iterator1.valid()) {
16 | console.log(iterator1.next());
17 | }
18 |
19 | console.log('');
20 | console.log('Reverse traversal:');
21 |
22 | // make reverse iterator
23 | const reverseIterator1 = collection1.getReverseIterator();
24 | while (reverseIterator1.valid()) {
25 | console.log(reverseIterator1.next());
26 | }
27 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/observer/example/editor/Editor.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.observer.example.editor;
2 |
3 | import refactoring_guru.observer.example.publisher.EventManager;
4 |
5 | import java.io.File;
6 |
7 | public class Editor {
8 | public EventManager events;
9 | private File file;
10 |
11 | public Editor() {
12 | this.events = new EventManager("open", "save");
13 | }
14 |
15 | public void openFile(String filePath) {
16 | this.file = new File(filePath);
17 | events.notify("open", file);
18 | }
19 |
20 | public void saveFile() throws Exception {
21 | if (this.file != null) {
22 | events.notify("save", file);
23 | } else {
24 | throw new Exception("Please open a file first.");
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/composite/example/shapes/Rectangle.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.composite.example.shapes;
2 |
3 | import java.awt.*;
4 |
5 | public class Rectangle extends BaseShape {
6 | public int width;
7 | public int height;
8 |
9 | public Rectangle(int x, int y, int width, int height, Color color) {
10 | super(x, y, color);
11 | this.width = width;
12 | this.height = height;
13 | }
14 |
15 | @Override
16 | public int getWidth() {
17 | return width;
18 | }
19 |
20 | @Override
21 | public int getHeight() {
22 | return height;
23 | }
24 |
25 | @Override
26 | public void paint(Graphics graphics) {
27 | super.paint(graphics);
28 | graphics.drawRect(x, y, getWidth() - 1, getHeight() - 1);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/memento/example/shapes/Rectangle.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.memento.example.shapes;
2 |
3 | import java.awt.*;
4 |
5 | public class Rectangle extends BaseShape {
6 | private int width;
7 | private int height;
8 |
9 | public Rectangle(int x, int y, int width, int height, Color color) {
10 | super(x, y, color);
11 | this.width = width;
12 | this.height = height;
13 | }
14 |
15 | @Override
16 | public int getWidth() {
17 | return width;
18 | }
19 |
20 | @Override
21 | public int getHeight() {
22 | return height;
23 | }
24 |
25 | @Override
26 | public void paint(Graphics graphics) {
27 | super.paint(graphics);
28 | graphics.drawRect(x, y, getWidth() - 1, getHeight() - 1);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/courses/guru/js/patterns/singleton/singleton.js:
--------------------------------------------------------------------------------
1 | // private data
2 | const privateObject = {
3 | username: 'sparx',
4 | password: 'superpassword',
5 | };
6 |
7 | // instance save
8 | let instance = null;
9 |
10 | class Singleton {
11 | constructor() {
12 | // if we have instance just return it
13 | if (instance) return instance;
14 | // else: save Singleton object to instance
15 | instance = this;
16 | // add private data to instance object
17 | return Object.assign(instance, privateObject);
18 | }
19 |
20 | // static method for instance access
21 | static getInstance() {
22 | // if we have instance just return it
23 | if (instance) return instance;
24 | // else: create instance of Singleton and return it
25 | return new Singleton();
26 | }
27 | }
28 |
29 | export { Singleton };
30 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/observer/example/Demo.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.observer.example;
2 |
3 | import refactoring_guru.observer.example.editor.Editor;
4 | import refactoring_guru.observer.example.listeners.EmailNotificationListener;
5 | import refactoring_guru.observer.example.listeners.LogOpenListener;
6 |
7 | public class Demo {
8 | public static void main(String[] args) {
9 | Editor editor = new Editor();
10 | editor.events.subscribe("open", new LogOpenListener("/path/to/log/file.txt"));
11 | editor.events.subscribe("save", new EmailNotificationListener("admin@example.com"));
12 |
13 | try {
14 | editor.openFile("test.txt");
15 | editor.saveFile();
16 | } catch (Exception e) {
17 | e.printStackTrace();
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/courses/guru/js/patterns/strategy/context.js:
--------------------------------------------------------------------------------
1 | // defines interface for Client interest
2 | // doesn't know concrete Strategy
3 | // should work with all Strategies using Strategy interface
4 | class Context {
5 | // reference to one of Strategy
6 | #strategy = null;
7 |
8 | // set Strategy through constructor
9 | constructor(strategy) {
10 | this.#strategy = strategy;
11 | }
12 |
13 | // set Strategy at runtime
14 | setStrategy(strategy) {
15 | this.#strategy = strategy;
16 | }
17 |
18 | // delegate work to Strategy instead of implementing multiple versions of algorithm
19 | businessLogic() {
20 | console.log('Context: sort data using some strategy...');
21 | const result = this.#strategy.doAlgorithm(['a', 'b', 'c', 'd', 'e']);
22 | console.log(result.join(','));
23 | }
24 | }
25 |
26 | export { Context };
27 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/memento/example/commands/ColorCommand.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.memento.example.commands;
2 |
3 | import refactoring_guru.memento.example.editor.Editor;
4 | import refactoring_guru.memento.example.shapes.Shape;
5 |
6 | import java.awt.*;
7 |
8 | public class ColorCommand implements Command {
9 | private Editor editor;
10 | private Color color;
11 |
12 | public ColorCommand(Editor editor, Color color) {
13 | this.editor = editor;
14 | this.color = color;
15 | }
16 |
17 | @Override
18 | public String getName() {
19 | return "Colorize: " + color.toString();
20 | }
21 |
22 | @Override
23 | public void execute() {
24 | for (Shape child : editor.getShapes().getSelected()) {
25 | child.setColor(color);
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/prototype/example/shapes/Shape.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.prototype.example.shapes;
2 |
3 | import java.util.Objects;
4 |
5 | public abstract class Shape {
6 | public int x;
7 | public int y;
8 | public String color;
9 |
10 | public Shape() {
11 | }
12 |
13 | public Shape(Shape target) {
14 | if (target != null) {
15 | this.x = target.x;
16 | this.y = target.y;
17 | this.color = target.color;
18 | }
19 | }
20 |
21 | public abstract Shape clone();
22 |
23 | @Override
24 | public boolean equals(Object object2) {
25 | if (!(object2 instanceof Shape)) return false;
26 | Shape shape2 = (Shape) object2;
27 | return shape2.x == x && shape2.y == y && Objects.equals(shape2.color, color);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/builder/example/builders/Builder.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.builder.example.builders;
2 |
3 | import refactoring_guru.builder.example.cars.Type;
4 | import refactoring_guru.builder.example.components.Engine;
5 | import refactoring_guru.builder.example.components.GPSNavigator;
6 | import refactoring_guru.builder.example.components.Transmission;
7 | import refactoring_guru.builder.example.components.TripComputer;
8 |
9 | /**
10 | * Builder interface defines all possible ways to configure a product.
11 | */
12 | public interface Builder {
13 | void setType(Type type);
14 | void setSeats(int seats);
15 | void setEngine(Engine engine);
16 | void setTransmission(Transmission transmission);
17 | void setTripComputer(TripComputer tripComputer);
18 | void setGPSNavigator(GPSNavigator gpsNavigator);
19 | }
20 |
--------------------------------------------------------------------------------
/courses/guru/js/examples/bridge.js:
--------------------------------------------------------------------------------
1 | import {
2 | Abstraction,
3 | AbstractionExtended,
4 | ImplementationA,
5 | ImplementationB,
6 | } from '../patterns/bridge';
7 |
8 | // client code should depend only on Abstraction class
9 | // this way client code can work with any abstraction-implementation combination
10 | function clientCode(abstraction) {
11 | console.log(abstraction.operation());
12 | }
13 |
14 | let implementation = null;
15 | let abstraction = null;
16 |
17 | /* --- combination: Abstraction-ImplementationA ---*/
18 | implementation = new ImplementationA();
19 | abstraction = new Abstraction(implementation);
20 | clientCode(abstraction);
21 |
22 | /* --- combination: AbstractionExtended-ImplementationB ---*/
23 | implementation = new ImplementationB();
24 | abstraction = new AbstractionExtended(implementation);
25 | clientCode(abstraction);
26 |
--------------------------------------------------------------------------------
/courses/guru/js/examples/observer.js:
--------------------------------------------------------------------------------
1 | import { Subject1, Observer1, Observer2 } from '../patterns/observer';
2 |
3 | // create subject
4 | const subject1 = new Subject1();
5 |
6 | // create observer
7 | const observer1 = new Observer1();
8 | // attach observer to subject
9 | subject1.attach(observer1);
10 |
11 | // create another observer
12 | const observer2 = new Observer2();
13 | // attach this observer to same subject
14 | subject1.attach(observer2);
15 |
16 | // execute some business logic methods
17 | // both observers will be notified about some event
18 | subject1.someBusinessLogic();
19 | subject1.someBusinessLogic();
20 |
21 | // detach second observer from subject
22 | subject1.detach(observer2);
23 |
24 | // execute some business logic methods again
25 | // now only first observer will be notified about some event
26 | subject1.someBusinessLogic();
27 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/abstract_factory/example/factories/MacOSFactory.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.abstract_factory.example.factories;
2 |
3 | import refactoring_guru.abstract_factory.example.buttons.Button;
4 | import refactoring_guru.abstract_factory.example.buttons.MacOSButton;
5 | import refactoring_guru.abstract_factory.example.checkboxes.Checkbox;
6 | import refactoring_guru.abstract_factory.example.checkboxes.MacOSCheckbox;
7 |
8 | /**
9 | * Each concrete factory extends basic factory and responsible for creating
10 | * products of a single variety.
11 | */
12 | public class MacOSFactory implements GUIFactory {
13 |
14 | @Override
15 | public Button createButton() {
16 | return new MacOSButton();
17 | }
18 |
19 | @Override
20 | public Checkbox createCheckbox() {
21 | return new MacOSCheckbox();
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/courses/guru/js/examples/decorator.js:
--------------------------------------------------------------------------------
1 | import {
2 | ComponentA,
3 | DecoratorA,
4 | DecoratorB,
5 | } from '../patterns/decorator';
6 |
7 | // works with all objects using Component interface
8 | // this way it can stay independent of concrete classes of components it works with
9 | function clientCode(component) {
10 | console.log(`RESULT: ${component.operation()}`);
11 | }
12 |
13 | /* --- working with simple components --- */
14 |
15 | const simpleComponent = new ComponentA();
16 | console.log('Client: Simple component:');
17 | clientCode(simpleComponent);
18 |
19 | /* --- working with decorated components --- */
20 |
21 | // wrap simple component
22 | const decoratorA = new DecoratorA(simpleComponent);
23 | // wrap decorated component
24 | const decoratorB = new DecoratorB(decoratorA);
25 | console.log('Client: Decorated component:');
26 | clientCode(decoratorB);
27 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/abstract_factory/example/factories/WindowsFactory.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.abstract_factory.example.factories;
2 |
3 | import refactoring_guru.abstract_factory.example.buttons.Button;
4 | import refactoring_guru.abstract_factory.example.buttons.WindowsButton;
5 | import refactoring_guru.abstract_factory.example.checkboxes.Checkbox;
6 | import refactoring_guru.abstract_factory.example.checkboxes.WindowsCheckbox;
7 |
8 | /**
9 | * Each concrete factory extends basic factory and responsible for creating
10 | * products of a single variety.
11 | */
12 | public class WindowsFactory implements GUIFactory {
13 |
14 | @Override
15 | public Button createButton() {
16 | return new WindowsButton();
17 | }
18 |
19 | @Override
20 | public Checkbox createCheckbox() {
21 | return new WindowsCheckbox();
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/abstract_factory/example/app/Application.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.abstract_factory.example.app;
2 |
3 | import refactoring_guru.abstract_factory.example.buttons.Button;
4 | import refactoring_guru.abstract_factory.example.checkboxes.Checkbox;
5 | import refactoring_guru.abstract_factory.example.factories.GUIFactory;
6 |
7 | /**
8 | * Factory users don't care which concrete factory they use since they work with
9 | * factories and products through abstract interfaces.
10 | */
11 | public class Application {
12 | private Button button;
13 | private Checkbox checkbox;
14 |
15 | public Application(GUIFactory factory) {
16 | button = factory.createButton();
17 | checkbox = factory.createCheckbox();
18 | }
19 |
20 | public void paint() {
21 | button.paint();
22 | checkbox.paint();
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/mediator/example/components/Title.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.mediator.example.components;
2 |
3 | import refactoring_guru.mediator.example.mediator.Mediator;
4 |
5 | import javax.swing.*;
6 | import java.awt.event.KeyEvent;
7 |
8 | /**
9 | * Concrete components don't talk with each other. They have only one
10 | * communication channel–sending requests to the mediator.
11 | */
12 | public class Title extends JTextField implements Component {
13 | private Mediator mediator;
14 |
15 | @Override
16 | public void setMediator(Mediator mediator) {
17 | this.mediator = mediator;
18 | }
19 |
20 | @Override
21 | protected void processComponentKeyEvent(KeyEvent keyEvent) {
22 | mediator.markNote();
23 | }
24 |
25 | @Override
26 | public String getName() {
27 | return "Title";
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/mediator/example/components/TextBox.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.mediator.example.components;
2 |
3 | import refactoring_guru.mediator.example.mediator.Mediator;
4 |
5 | import javax.swing.*;
6 | import java.awt.event.KeyEvent;
7 |
8 | /**
9 | * Concrete components don't talk with each other. They have only one
10 | * communication channel–sending requests to the mediator.
11 | */
12 | public class TextBox extends JTextArea implements Component {
13 | private Mediator mediator;
14 |
15 | @Override
16 | public void setMediator(Mediator mediator) {
17 | this.mediator = mediator;
18 | }
19 |
20 | @Override
21 | protected void processComponentKeyEvent(KeyEvent keyEvent) {
22 | mediator.markNote();
23 | }
24 |
25 | @Override
26 | public String getName() {
27 | return "TextBox";
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/prototype/example/shapes/Rectangle.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.prototype.example.shapes;
2 |
3 | public class Rectangle extends Shape {
4 | public int width;
5 | public int height;
6 |
7 | public Rectangle() {
8 | }
9 |
10 | public Rectangle(Rectangle target) {
11 | super(target);
12 | if (target != null) {
13 | this.width = target.width;
14 | this.height = target.height;
15 | }
16 | }
17 |
18 | @Override
19 | public Shape clone() {
20 | return new Rectangle(this);
21 | }
22 |
23 | @Override
24 | public boolean equals(Object object2) {
25 | if (!(object2 instanceof Rectangle) || !super.equals(object2)) return false;
26 | Rectangle shape2 = (Rectangle) object2;
27 | return shape2.width == width && shape2.height == height;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/state/example/states/PlayingState.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.state.example.states;
2 |
3 | import refactoring_guru.state.example.ui.Player;
4 |
5 | public class PlayingState extends State {
6 |
7 | PlayingState(Player player) {
8 | super(player);
9 | }
10 |
11 | @Override
12 | public String onLock() {
13 | player.changeState(new LockedState(player));
14 | player.setCurrentTrackAfterStop();
15 | return "Stop playing";
16 | }
17 |
18 | @Override
19 | public String onPlay() {
20 | player.changeState(new ReadyState(player));
21 | return "Paused...";
22 | }
23 |
24 | @Override
25 | public String onNext() {
26 | return player.nextTrack();
27 | }
28 |
29 | @Override
30 | public String onPrevious() {
31 | return player.previousTrack();
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/courses/guru/php/src/RefactoringGuru/Bridge/RealWorld/Output.txt:
--------------------------------------------------------------------------------
1 | HTML view of a simple content page:
2 |
3 | Home
4 | Welcome to our website!
5 |
6 |
7 | JSON view of a simple content page, rendered with the same client code:
8 | {
9 | "title": "Home",
10 | "text": "Welcome to our website!"
11 | }
12 |
13 | HTML view of a product page, same client code:
14 |
15 | Star Wars, episode1
16 | A long time ago in a galaxy far, far away...
17 |
18 | Add to cart
19 |
20 |
21 | JSON view of a simple content page, with the same client code:
22 | {
23 | "title": "Star Wars, episode1",
24 | "text": "A long time ago in a galaxy far, far away...",
25 | "img": "/images/star-wars.jpeg",
26 | "link": {"href": "Add to cart", "title": "Add to cart""}
27 | }
--------------------------------------------------------------------------------
/courses/guru/js/examples/visitor.js:
--------------------------------------------------------------------------------
1 | import {
2 | Component1,
3 | Component2,
4 | Visitor1,
5 | Visitor2,
6 | } from '../patterns/visitor';
7 |
8 | // client code can run operations on any set of elements without figuring out their concrete classes
9 | function clientCode(components, visitor) {
10 | components.forEach((component) => {
11 | component.accept(visitor);
12 | });
13 | }
14 |
15 | // create components
16 | const components = [
17 | new Component1(),
18 | new Component2(),
19 | ];
20 |
21 | /* --- use one Visitor --- */
22 |
23 | console.log('Client code works with all visitors using Visitor interface:');
24 | const visitor1 = new Visitor1();
25 | clientCode(components, visitor1);
26 |
27 | console.log('');
28 |
29 | /* --- use another Visitor --- */
30 |
31 | console.log('Same client can work with another Visitor:');
32 | const visitor2 = new Visitor2();
33 | clientCode(components, visitor2);
34 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/visitor/example/OutputDemo.txt:
--------------------------------------------------------------------------------
1 |
2 |
3 | 2
4 | 23
5 | 15
6 | 10
7 |
8 |
9 |
10 |
11 | 4
12 |
13 | 1
14 | 10
15 | 55
16 |
17 |
18 | 2
19 | 23
20 | 15
21 | 10
22 |
23 |
24 | 3
25 | 10
26 | 17
27 | 20
28 | 30
29 |
30 |
31 | 5
32 |
33 | 1
34 | 10
35 | 55
36 |
37 |
38 |
--------------------------------------------------------------------------------
/courses/guru/php/src/RefactoringGuru/FactoryMethod/RealWorld/Output.txt:
--------------------------------------------------------------------------------
1 | Testing ConcreteCreator1:
2 | Send HTTP API request to log in user john_smith with password ******
3 | Send HTTP API requests to create a post in Facebook timeline.
4 | Send HTTP API request to log out user john_smith
5 | Send HTTP API request to log in user john_smith with password ******
6 | Send HTTP API requests to create a post in Facebook timeline.
7 | Send HTTP API request to log out user john_smith
8 |
9 |
10 | Testing ConcreteCreator2:
11 | Send HTTP API request to log in user john_smith@example.com with password ******
12 | Send HTTP API requests to create a post in LinkedIn timeline.
13 | Send HTTP API request to log out user john_smith@example.com
14 | Send HTTP API request to log in user john_smith@example.com with password ******
15 | Send HTTP API requests to create a post in LinkedIn timeline.
16 | Send HTTP API request to log out user john_smith@example.com
17 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/state/example/states/ReadyState.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.state.example.states;
2 |
3 | import refactoring_guru.state.example.ui.Player;
4 |
5 | /**
6 | * They can also trigger state transitions in the context.
7 | */
8 | public class ReadyState extends State {
9 |
10 | public ReadyState(Player player) {
11 | super(player);
12 | }
13 |
14 | @Override
15 | public String onLock() {
16 | player.changeState(new LockedState(player));
17 | return "Locked...";
18 | }
19 |
20 | @Override
21 | public String onPlay() {
22 | String action = player.startPlayback();
23 | player.changeState(new PlayingState(player));
24 | return action;
25 | }
26 |
27 | @Override
28 | public String onNext() {
29 | return "Locked...";
30 | }
31 |
32 | @Override
33 | public String onPrevious() {
34 | return "Locked...";
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/flyweight/example/forest/Forest.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.flyweight.example.forest;
2 |
3 | import refactoring_guru.flyweight.example.trees.Tree;
4 | import refactoring_guru.flyweight.example.trees.TreeFactory;
5 | import refactoring_guru.flyweight.example.trees.TreeType;
6 |
7 | import javax.swing.*;
8 | import java.awt.*;
9 | import java.util.ArrayList;
10 | import java.util.List;
11 |
12 | public class Forest extends JFrame {
13 | private List trees = new ArrayList<>();
14 |
15 | public void plantTree(int x, int y, String name, Color color, String otherTreeData) {
16 | TreeType type = TreeFactory.getTreeType(name, color, otherTreeData);
17 | Tree tree = new Tree(x, y, type);
18 | trees.add(tree);
19 | }
20 |
21 | @Override
22 | public void paint(Graphics graphics) {
23 | for (Tree tree : trees) {
24 | tree.draw(graphics);
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/template_method/example/networks/Network.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.template_method.example.networks;
2 |
3 | /**
4 | * Base class of social network.
5 | */
6 | public abstract class Network {
7 | String userName;
8 | String password;
9 |
10 | Network() {}
11 |
12 | /**
13 | * Publish the data to whatever network.
14 | */
15 | public boolean post(String message) {
16 | // Authenticate before posting. Every network uses a different
17 | // authentication method.
18 | if (logIn(this.userName, this.password)) {
19 | // Send the post data.
20 | boolean result = sendData(message.getBytes());
21 | logOut();
22 | return result;
23 | }
24 | return false;
25 | }
26 |
27 | abstract boolean logIn(String userName, String password);
28 | abstract boolean sendData(byte[] data);
29 | abstract void logOut();
30 | }
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/visitor/example/shapes/CompoundShape.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.visitor.example.shapes;
2 |
3 | import refactoring_guru.visitor.example.visitor.Visitor;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | public class CompoundShape implements Shape {
9 | public int id;
10 | public List children = new ArrayList<>();
11 |
12 | public CompoundShape(int id) {
13 | this.id = id;
14 | }
15 |
16 | @Override
17 | public void move(int x, int y) {
18 | // move shape
19 | }
20 |
21 | @Override
22 | public void draw() {
23 | // draw shape
24 | }
25 |
26 | public int getId() {
27 | return id;
28 | }
29 |
30 | @Override
31 | public String accept(Visitor visitor) {
32 | return visitor.visitCompoundGraphic(this);
33 | }
34 |
35 | public void add(Shape shape) {
36 | children.add(shape);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/command/example/commands/CutCommand.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.command.example.commands;
2 |
3 | import refactoring_guru.command.example.editor.Editor;
4 |
5 | public class CutCommand extends Command {
6 |
7 | public CutCommand(Editor editor) {
8 | super(editor);
9 | }
10 |
11 | @Override
12 | public boolean execute() {
13 | if (editor.textField.getSelectedText().isEmpty()) return false;
14 |
15 | backup();
16 | String source = editor.textField.getText();
17 | editor.clipboard = editor.textField.getSelectedText();
18 | editor.textField.setText(cutString(source));
19 | return true;
20 | }
21 |
22 | private String cutString(String source) {
23 | String start = source.substring(0, editor.textField.getSelectionStart());
24 | String end = source.substring(editor.textField.getSelectionEnd());
25 | return start + end;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/mediator/example/components/DeleteButton.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.mediator.example.components;
2 |
3 | import refactoring_guru.mediator.example.mediator.Mediator;
4 |
5 | import javax.swing.*;
6 | import java.awt.event.ActionEvent;
7 |
8 | /**
9 | * Concrete components don't talk with each other. They have only one
10 | * communication channel–sending requests to the mediator.
11 | */
12 | public class DeleteButton extends JButton implements Component {
13 | private Mediator mediator;
14 |
15 | public DeleteButton() {
16 | super("Del");
17 | }
18 |
19 | @Override
20 | public void setMediator(Mediator mediator) {
21 | this.mediator = mediator;
22 | }
23 |
24 | @Override
25 | protected void fireActionPerformed(ActionEvent actionEvent) {
26 | mediator.deleteNote();
27 | }
28 |
29 | @Override
30 | public String getName() {
31 | return "DelButton";
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/mediator/example/components/SaveButton.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.mediator.example.components;
2 |
3 | import refactoring_guru.mediator.example.mediator.Mediator;
4 |
5 | import javax.swing.*;
6 | import java.awt.event.ActionEvent;
7 |
8 | /**
9 | * Concrete components don't talk with each other. They have only one
10 | * communication channel–sending requests to the mediator.
11 | */
12 | public class SaveButton extends JButton implements Component {
13 | private Mediator mediator;
14 |
15 | public SaveButton() {
16 | super("Save");
17 | }
18 |
19 | @Override
20 | public void setMediator(Mediator mediator) {
21 | this.mediator = mediator;
22 | }
23 |
24 | @Override
25 | protected void fireActionPerformed(ActionEvent actionEvent) {
26 | mediator.saveChanges();
27 | }
28 |
29 | @Override
30 | public String getName() {
31 | return "SaveButton";
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/visitor/example/shapes/Dot.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.visitor.example.shapes;
2 |
3 | import refactoring_guru.visitor.example.visitor.Visitor;
4 |
5 | public class Dot implements Shape {
6 | private int id;
7 | private int x;
8 | private int y;
9 |
10 | public Dot() {
11 | }
12 |
13 | public Dot(int id, int x, int y) {
14 | this.id = id;
15 | this.x = x;
16 | this.y = y;
17 | }
18 |
19 | @Override
20 | public void move(int x, int y) {
21 | // move shape
22 | }
23 |
24 | @Override
25 | public void draw() {
26 | // draw shape
27 | }
28 |
29 | public String accept(Visitor visitor) {
30 | return visitor.visitDot(this);
31 | }
32 |
33 | public int getX() {
34 | return x;
35 | }
36 |
37 | public int getY() {
38 | return y;
39 | }
40 |
41 | public int getId() {
42 | return id;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/mediator/example/Demo.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.mediator.example;
2 |
3 | import refactoring_guru.mediator.example.components.*;
4 | import refactoring_guru.mediator.example.mediator.Editor;
5 | import refactoring_guru.mediator.example.mediator.Mediator;
6 |
7 | import javax.swing.*;
8 |
9 | /**
10 | * Demo class. Everything comes together here.
11 | */
12 | public class Demo {
13 | public static void main(String[] args) {
14 | Mediator mediator = new Editor();
15 |
16 | mediator.registerComponent(new Title());
17 | mediator.registerComponent(new TextBox());
18 | mediator.registerComponent(new AddButton());
19 | mediator.registerComponent(new DeleteButton());
20 | mediator.registerComponent(new SaveButton());
21 | mediator.registerComponent(new List(new DefaultListModel()));
22 | mediator.registerComponent(new Filter());
23 |
24 | mediator.createGUI();
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/chain_of_responsibility/example/middleware/UserExistsMiddleware.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.chain_of_responsibility.example.middleware;
2 |
3 | import refactoring_guru.chain_of_responsibility.example.server.Server;
4 |
5 | /**
6 | * ConcreteHandler. Checks whether a user with the given credentials exists.
7 | */
8 | public class UserExistsMiddleware extends Middleware {
9 | private Server server;
10 |
11 | public UserExistsMiddleware(Server server) {
12 | this.server = server;
13 | }
14 |
15 | public boolean check(String email, String password) {
16 | if (!server.hasEmail(email)) {
17 | System.out.println("This email is not registered!");
18 | return false;
19 | }
20 | if (!server.isValidPassword(email, password)) {
21 | System.out.println("Wrong password!");
22 | return false;
23 | }
24 | return checkNext(email, password);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/chain_of_responsibility/example/middleware/Middleware.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.chain_of_responsibility.example.middleware;
2 |
3 | /**
4 | * Base middleware class.
5 | */
6 | public abstract class Middleware {
7 | private Middleware next;
8 |
9 | /**
10 | * Builds chains of middleware objects.
11 | */
12 | public Middleware linkWith(Middleware next) {
13 | this.next = next;
14 | return next;
15 | }
16 |
17 | /**
18 | * Subclasses will implement this method with concrete checks.
19 | */
20 | public abstract boolean check(String email, String password);
21 |
22 | /**
23 | * Runs check on the next object in chain or ends traversing if we're in
24 | * last object in chain.
25 | */
26 | protected boolean checkNext(String email, String password) {
27 | if (next == null) {
28 | return true;
29 | }
30 | return next.check(email, password);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/courses/guru/php/src/RefactoringGuru/Iterator/RealWorld/Output.txt:
--------------------------------------------------------------------------------
1 | Array
2 | (
3 | [0] => Name
4 | [1] => Age
5 | [2] => Owner
6 | [3] => Breed
7 | [4] => Image
8 | [5] => Color
9 | [6] => Texture
10 | [7] => Fur
11 | [8] => Size
12 | )
13 | Array
14 | (
15 | [0] => Steve
16 | [1] => 3
17 | [2] => Alexander Shvets
18 | [3] => Bengal
19 | [4] => /cats/bengal.jpg
20 | [5] => Brown
21 | [6] => Stripes
22 | [7] => Short
23 | [8] => Medium
24 | )
25 | Array
26 | (
27 | [0] => Siri
28 | [1] => 2
29 | [2] => Alexander Shvets
30 | [3] => Domestic short-haired
31 | [4] => /cats/domestic-sh.jpg
32 | [5] => Black
33 | [6] => Solid
34 | [7] => Medium
35 | [8] => Medium
36 | )
37 | Array
38 | (
39 | [0] => Fluffy
40 | [1] => 5
41 | [2] => John Smith
42 | [3] => Maine Coon
43 | [4] => /cats/Maine-Coon.jpg
44 | [5] => Gray
45 | [6] => Stripes
46 | [7] => Long
47 | [8] => Large
48 | )
49 |
--------------------------------------------------------------------------------
/courses/guru/js/patterns/mediator/mediators/mediator1.js:
--------------------------------------------------------------------------------
1 | /* --- references to connected components --- */
2 | let component1 = null;
3 | let component2 = null;
4 |
5 | // concrete Mediator implement cooperative behavior by coordinating several components
6 | class Mediator1 {
7 | constructor(c1, c2) {
8 | component1 = c1;
9 | component1.mediator = this;
10 |
11 | component2 = c2;
12 | component2.mediator = this;
13 | }
14 |
15 | // method used by components to notify Mediator about some events
16 | // Mediator may react to these events and pass execution to other components
17 | notify(sender, event) {
18 | if (event === 'A') {
19 | console.log('Mediator1 react on event A and trigger following operations:');
20 | component2.doC();
21 | }
22 |
23 | if (event === 'D') {
24 | console.log('Mediator1 react on event D and trigger following operations:');
25 | component1.doB();
26 | component2.doC();
27 | }
28 | }
29 | }
30 |
31 | export { Mediator1 };
32 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/bridge/example/OutputDemo.txt:
--------------------------------------------------------------------------------
1 | Tests with basic remote.
2 | Remote: power toggle
3 | ------------------------------------
4 | | I'm TV set.
5 | | I'm enabled
6 | | Current volume is 30%
7 | | Current channel is 1
8 | ------------------------------------
9 |
10 | Tests with advanced remote.
11 | Remote: power toggle
12 | Remote: mute
13 | ------------------------------------
14 | | I'm TV set.
15 | | I'm disabled
16 | | Current volume is 0%
17 | | Current channel is 1
18 | ------------------------------------
19 |
20 | Tests with basic remote.
21 | Remote: power toggle
22 | ------------------------------------
23 | | I'm radio.
24 | | I'm enabled
25 | | Current volume is 30%
26 | | Current channel is 1
27 | ------------------------------------
28 |
29 | Tests with advanced remote.
30 | Remote: power toggle
31 | Remote: mute
32 | ------------------------------------
33 | | I'm radio.
34 | | I'm disabled
35 | | Current volume is 0%
36 | | Current channel is 1
37 | ------------------------------------
--------------------------------------------------------------------------------
/courses/guru/php/src/RefactoringGuru/Decorator/RealWorld/Output.txt:
--------------------------------------------------------------------------------
1 | Website renders comments without filtering (unsafe):
2 | Hello! Nice blog post!
3 | Please visit my homepage.
4 |
7 |
8 |
9 | Website renders comments after stripping all tags (safe):
10 | Hello! Nice blog post!
11 | Please visit my homepage.
12 |
13 | performXSSAttack();
14 |
15 |
16 |
17 | Website renders a forum post without filtering and formatting (unsafe, ugly):
18 | # Welcome
19 |
20 | This is my first post on this **gorgeous** forum.
21 |
22 |
25 |
26 |
27 | Website renders a forum post after translating markdown markupand filtering some dangerous HTML tags and attributes (safe, pretty):
28 | Welcome
29 |
30 | This is my first post on this gorgeous forum.
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ""
5 | labels: ""
6 | assignees: ""
7 | ---
8 |
9 | **Describe the bug**
10 | A clear and concise description of what the bug is.
11 |
12 | **To Reproduce**
13 | Steps to reproduce the behavior:
14 |
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 |
28 | - OS: [e.g. iOS]
29 | - Browser [e.g. chrome, safari]
30 | - Version [e.g. 22]
31 |
32 | **Smartphone (please complete the following information):**
33 |
34 | - Device: [e.g. iPhone6]
35 | - OS: [e.g. iOS8.1]
36 | - Browser [e.g. stock browser, safari]
37 | - Version [e.g. 22]
38 |
39 | **Additional context**
40 | Add any other context about the problem here.
41 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/decorator/example/Demo.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.decorator.example;
2 |
3 | import refactoring_guru.decorator.example.decorators.*;
4 |
5 | public class Demo {
6 | public static void main(String[] args) {
7 | String salaryRecords = "Name,Salary\nJohn Smith,100000\nSteven Jobs,912000";
8 | DataSourceDecorator encoded = new CompressionDecorator(
9 | new EncryptionDecorator(
10 | new FileDataSource("out/OutputDemo.txt")));
11 | encoded.writeData(salaryRecords);
12 | DataSource plain = new FileDataSource("out/OutputDemo.txt");
13 |
14 | System.out.println("- Input ----------------");
15 | System.out.println(salaryRecords);
16 | System.out.println("- Encoded --------------");
17 | System.out.println(plain.readData());
18 | System.out.println("- Decoded --------------");
19 | System.out.println(encoded.readData());
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/courses/guru/php/src/RefactoringGuru/Visitor/RealWorld/Output.txt:
--------------------------------------------------------------------------------
1 | Client: I can print a report for a whole company:
2 |
3 | SuperStarDevelopment (USD550,000.00)
4 |
5 | --Mobile Development (USD351,000.00)
6 |
7 | $100,000.00 Albert Falmore (designer)
8 | $100,000.00 Ali Halabay (programmer)
9 | $ 90,000.00 Sarah Konor (programmer)
10 | $ 31,000.00 Monica Ronaldino (QA engineer)
11 | $ 30,000.00 James Smith (QA engineer)
12 |
13 | --Tech Support (USD199,000.00)
14 |
15 | $ 70,000.00 Larry Ulbrecht (supervisor)
16 | $ 30,000.00 Elton Pale (operator)
17 | $ 30,000.00 Rajeet Kumar (operator)
18 | $ 34,000.00 John Burnovsky (operator)
19 | $ 35,000.00 Sergey Korolev (operator)
20 |
21 | Client: ...or just for a single department:
22 |
23 | Tech Support (USD199,000.00)
24 |
25 | $ 70,000.00 Larry Ulbrecht (supervisor)
26 | $ 30,000.00 Elton Pale (operator)
27 | $ 30,000.00 Rajeet Kumar (operator)
28 | $ 34,000.00 John Burnovsky (operator)
29 | $ 35,000.00 Sergey Korolev (operator)
--------------------------------------------------------------------------------
/courses/guru/c#/RefactoringGuru.DesignPatterns.Flyweight.Structural/Output.txt:
--------------------------------------------------------------------------------
1 | FlyweightFactory: I have 5 flyweights:
2 | Camaro2018_Chevrolet_pink
3 | black_C300_Mercedes Benz
4 | C500_Mercedes Benz_red
5 | BMW_M5_red
6 | BMW_white_X6
7 |
8 | Client: Adding a car to database.
9 | FlyweightFactory: Reusing existing flyweight.
10 | Flyweight: Displaying shared {"Owner":null,"Number":null,"Company":"BMW","Model":"M5","Color":"red"} and unique {"Owner":"James Doe","Number":"CL234IR","Company":"BMW","Model":"M5","Color":"red"} state.
11 |
12 | Client: Adding a car to database.
13 | FlyweightFactory: Can't find a flyweight, creating new one.
14 | Flyweight: Displaying shared {"Owner":null,"Number":null,"Company":"BMW","Model":"X1","Color":"red"} and unique {"Owner":"James Doe","Number":"CL234IR","Company":"BMW","Model":"X1","Color":"red"} state.
15 |
16 | FlyweightFactory: I have 6 flyweights:
17 | Camaro2018_Chevrolet_pink
18 | black_C300_Mercedes Benz
19 | C500_Mercedes Benz_red
20 | BMW_M5_red
21 | BMW_white_X6
22 | BMW_red_X1
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/iterator/example/OutputDemo.txt:
--------------------------------------------------------------------------------
1 | Please specify social network to target spam tool (default:Facebook):
2 | 1. Facebook
3 | 2. LinkedIn
4 | > 1
5 |
6 | Iterating over friends...
7 |
8 | Facebook: Loading 'friends' list of 'anna.smith@bing.com' over the network...
9 | Facebook: Loading profile 'mad_max@ya.com' over the network...
10 | Sent message to: 'mad_max@ya.com'. Message body: 'Hey! This is Anna's friend Josh. Can you do me a favor and like this post [link]?'
11 | Facebook: Loading profile 'catwoman@yahoo.com' over the network...
12 | Sent message to: 'catwoman@yahoo.com'. Message body: 'Hey! This is Anna's friend Josh. Can you do me a favor and like this post [link]?'
13 |
14 | Iterating over coworkers...
15 |
16 | Facebook: Loading 'coworkers' list of 'anna.smith@bing.com' over the network...
17 | Facebook: Loading profile 'sam@amazon.com' over the network...
18 | Sent message to: 'sam@amazon.com'. Message body: 'Hey! This is Anna's boss Jason. Anna told me you would be interested in [link].'
19 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/visitor/example/Demo.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.visitor.example;
2 |
3 | import refactoring_guru.visitor.example.shapes.*;
4 | import refactoring_guru.visitor.example.visitor.XMLExportVisitor;
5 |
6 | public class Demo {
7 | public static void main(String[] args) {
8 | Dot dot = new Dot(1, 10, 55);
9 | Circle circle = new Circle(2, 23, 15, 10);
10 | Rectangle rectangle = new Rectangle(3, 10, 17, 20, 30);
11 |
12 | CompoundShape compoundShape = new CompoundShape(4);
13 | compoundShape.add(dot);
14 | compoundShape.add(circle);
15 | compoundShape.add(rectangle);
16 |
17 | CompoundShape c = new CompoundShape(5);
18 | c.add(dot);
19 | compoundShape.add(c);
20 |
21 | export(circle, compoundShape);
22 | }
23 |
24 | private static void export(Shape... shapes) {
25 | XMLExportVisitor exportVisitor = new XMLExportVisitor();
26 | System.out.println(exportVisitor.export(shapes));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/mediator/example/components/AddButton.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.mediator.example.components;
2 |
3 | import refactoring_guru.mediator.example.mediator.Mediator;
4 | import refactoring_guru.mediator.example.mediator.Note;
5 |
6 | import javax.swing.*;
7 | import java.awt.event.ActionEvent;
8 |
9 | /**
10 | * Concrete components don't talk with each other. They have only one
11 | * communication channel–sending requests to the mediator.
12 | */
13 | public class AddButton extends JButton implements Component {
14 | private Mediator mediator;
15 |
16 | public AddButton() {
17 | super("Add");
18 | }
19 |
20 | @Override
21 | public void setMediator(Mediator mediator) {
22 | this.mediator = mediator;
23 | }
24 |
25 | @Override
26 | protected void fireActionPerformed(ActionEvent actionEvent) {
27 | mediator.addNewNote(new Note());
28 | }
29 |
30 | @Override
31 | public String getName() {
32 | return "AddButton";
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/courses/guru/js/patterns/builder/builders/builder1.js:
--------------------------------------------------------------------------------
1 | import { Product1 } from './product1';
2 |
3 | // implementation of building steps for concrete builder
4 | class Builder1 {
5 | // builder instance must have blank product object, which is used in further product assembly
6 | constructor() {
7 | this.reset();
8 | }
9 |
10 | reset() {
11 | this.product = new Product1();
12 | }
13 |
14 | // all production steps working with same product instance
15 | producePartA() {
16 | this.product.parts.push('PART-A-1');
17 | }
18 |
19 | producePartB() {
20 | this.product.parts.push('PART-B-1');
21 | }
22 |
23 | producePartC() {
24 | this.product.parts.push('PART-C-1');
25 | }
26 |
27 | // return result to client and reset for building next product (optionally)
28 | getProduct() {
29 | const result = this.product;
30 | // this is optional: builder can wait for explicit reset call from client before result return
31 | this.reset();
32 | return result;
33 | }
34 | }
35 |
36 | export { Builder1 };
37 |
--------------------------------------------------------------------------------
/courses/guru/js/patterns/builder/builders/builder2.js:
--------------------------------------------------------------------------------
1 | import { Product2 } from './product2';
2 |
3 | // implementation of building steps for concrete builder
4 | class Builder2 {
5 | // builder instance must have blank product object, which is used in further product assembly
6 | constructor() {
7 | this.reset();
8 | }
9 |
10 | reset() {
11 | this.product = new Product2();
12 | }
13 |
14 | // all production steps working with same product instance
15 | producePartA() {
16 | this.product.parts.push('PART-A-2');
17 | }
18 |
19 | producePartB() {
20 | this.product.parts.push('PART-B-2');
21 | }
22 |
23 | producePartC() {
24 | this.product.parts.push('PART-C-2');
25 | }
26 |
27 | // return result to client and reset for building next product (optionally)
28 | getProduct() {
29 | const result = this.product;
30 | // this is optional: builder can wait for explicit reset call from client before result return
31 | this.reset();
32 | return result;
33 | }
34 | }
35 |
36 | export { Builder2 };
37 |
--------------------------------------------------------------------------------
/courses/guru/js/patterns/facade/facade.js:
--------------------------------------------------------------------------------
1 | import { Subsystem1, Subsystem2 } from './subsystems';
2 |
3 | // provides simple interface to complex logic of one or many subsystems
4 | // delegates client requests to appropriate objects within subsystem
5 | class Facade {
6 | // Facade can be provided with existing subsystem objects or be forced to create its own
7 | constructor(subsystem1, subsystem2) {
8 | this.subsystem1 = subsystem1 || new Subsystem1();
9 | this.subsystem2 = subsystem2 || new Subsystem2();
10 | }
11 |
12 | // this method is shortcut to subsystems functionality
13 | // i.e. it "hides" some complexity behind simple interface
14 | operation() {
15 | let result = 'Facade initializes subsystems\n';
16 | result += this.subsystem1.operation1();
17 | result += this.subsystem2.operation1();
18 | result += 'Facade orders subsytems to perform action:\n';
19 | result += this.subsystem1.operationN();
20 | result += this.subsystem2.operationZ();
21 | return result;
22 | }
23 | }
24 |
25 | export { Facade };
26 |
--------------------------------------------------------------------------------
/courses/guru/js/patterns/template-method/operations/operation.js:
--------------------------------------------------------------------------------
1 | // define skeleton of algorithm composed from primitive operations
2 | class Operation {
3 | // algorithm skeleton
4 | templateMethod() {
5 | this.baseOperation1();
6 | this.requredOperation1();
7 | this.baseOperation2();
8 | this.hook1();
9 | this.requredOperation2();
10 | this.baseOperation3();
11 | this.hook2();
12 | }
13 |
14 | /* --- default operations implementation --- */
15 | baseOperation1() {
16 | console.log('Operation: do base operation 1.');
17 | }
18 |
19 | baseOperation2() {
20 | console.log('Operation: do base operation 2.');
21 | }
22 |
23 | baseOperation3() {
24 | console.log('Operation: do base operation 3.');
25 | }
26 |
27 | /* --- operations implemented in subclasses --- */
28 | requredOperation1() {}
29 |
30 | requredOperation2() {}
31 |
32 | /* --- these methods provide additional extension points somewhere in algoriythm --- */
33 | hook1() {}
34 |
35 | hook2() {}
36 | }
37 |
38 | export { Operation };
39 |
--------------------------------------------------------------------------------
/courses/guru/js/examples/abstract-factory.js:
--------------------------------------------------------------------------------
1 | import { Factory1, Factory2 } from '../patterns/abstract-factory';
2 |
3 | /* --- create products of type 1 --- */
4 |
5 | // use concrete factory
6 | let factory = new Factory1();
7 | // create product of family A
8 | let productA = factory.createProductA();
9 | // create product of family B
10 | let productB = factory.createProductB();
11 |
12 | // call product A method
13 | console.log('Factory #1: %s', productA.productAMethod());
14 | // call product B method
15 | console.log('Factory #1: %s', productB.productBMethod());
16 |
17 | /* --- create products of type 2 --- */
18 |
19 | // use concrete factory
20 | factory = new Factory2();
21 | // create product of family A
22 | productA = factory.createProductA();
23 | // create product of family B
24 | productB = factory.createProductB();
25 |
26 | // call product A method
27 | console.log('Factory #2: %s', productA.productAMethod());
28 | // call product B method collaborating with product of family A
29 | console.log('Factory #2: %s', productB.productBMethod2(productA));
30 |
--------------------------------------------------------------------------------
/courses/guru/js/examples/chain-of-responsibility.js:
--------------------------------------------------------------------------------
1 | import { Handler1, Handler2, Handler3 } from '../patterns/chain-of-responsibility';
2 |
3 | // client code usually suited to work with single handler
4 | // in most cases it is not even aware that handler is part of chain
5 | function clientCode(handler) {
6 | const requests = [1, 2, 3];
7 | requests.forEach((request) => {
8 | console.log(`Client: who can handle ${request}`);
9 | const result = handler.handle(request);
10 | if (result) {
11 | console.log(` ${result}`);
12 | } else {
13 | console.log(` Nobody can handle ${result}`);
14 | }
15 | });
16 | }
17 |
18 | /* --- build chain --- */
19 | const handler1 = new Handler1();
20 | const handler2 = new Handler2();
21 | const handler3 = new Handler3();
22 |
23 | handler1.setNext(handler2).setNext(handler3);
24 |
25 | /* --- sending requests --- */
26 |
27 | // all handlers
28 | console.log('Chain: 1 -> 2 -> 3\n');
29 | clientCode(handler1);
30 |
31 | // some of handlers
32 | console.log('Subchain: 2 -> 3\n');
33 | clientCode(handler2);
34 |
--------------------------------------------------------------------------------
/courses/guru/js/patterns/command/invokers/invoker1.js:
--------------------------------------------------------------------------------
1 | let onStart = null;
2 | let onFinish = null;
3 |
4 | function isCommand(object) {
5 | return object.execute !== undefined;
6 | }
7 |
8 | // associated with one or several commands
9 | // it sends request to command
10 | class Invoker1 {
11 | // initialize command
12 | setOnStart(command) {
13 | onStart = command;
14 | }
15 |
16 | // initialize command
17 | setOnFinish(command) {
18 | onFinish = command;
19 | }
20 |
21 | // Invoker doesn't depend on concrete Command or Receiver
22 | // it pass request to Receiver indirectly by executing some Command
23 | doSmthImportant() {
24 | console.log('Invoker1: Does anybody want something done before I begin?');
25 | if (isCommand) {
26 | onStart.execute();
27 | }
28 |
29 | console.log('Invoker1: ...doing something really important...');
30 | console.log('Invoker1: Does anybody want something done after I finish?');
31 | if (isCommand) {
32 | onFinish.execute();
33 | }
34 | }
35 | }
36 |
37 | export { Invoker1 };
38 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/bridge/example/Demo.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.bridge.example;
2 |
3 | import refactoring_guru.bridge.example.devices.Device;
4 | import refactoring_guru.bridge.example.devices.Radio;
5 | import refactoring_guru.bridge.example.devices.Tv;
6 | import refactoring_guru.bridge.example.remotes.AdvancedRemote;
7 | import refactoring_guru.bridge.example.remotes.BasicRemote;
8 |
9 | public class Demo {
10 | public static void main(String[] args) {
11 | testDevice(new Tv());
12 | testDevice(new Radio());
13 | }
14 |
15 | public static void testDevice(Device device) {
16 | System.out.println("Tests with basic remote.");
17 | BasicRemote basicRemote = new BasicRemote(device);
18 | basicRemote.power();
19 | device.printStatus();
20 |
21 | System.out.println("Tests with advanced remote.");
22 | AdvancedRemote advancedRemote = new AdvancedRemote(device);
23 | advancedRemote.power();
24 | advancedRemote.mute();
25 | device.printStatus();
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/state/example/states/LockedState.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.state.example.states;
2 |
3 | import refactoring_guru.state.example.ui.Player;
4 |
5 | /**
6 | * Concrete states provide the special implementation for all interface methods.
7 | */
8 | public class LockedState extends State {
9 |
10 | LockedState(Player player) {
11 | super(player);
12 | player.setPlaying(false);
13 | }
14 |
15 | @Override
16 | public String onLock() {
17 | if (player.isPlaying()) {
18 | player.changeState(new ReadyState(player));
19 | return "Stop playing";
20 | } else {
21 | return "Locked...";
22 | }
23 | }
24 |
25 | @Override
26 | public String onPlay() {
27 | player.changeState(new ReadyState(player));
28 | return "Ready";
29 | }
30 |
31 | @Override
32 | public String onNext() {
33 | return "Locked...";
34 | }
35 |
36 | @Override
37 | public String onPrevious() {
38 | return "Locked...";
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/builder/example/components/Engine.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.builder.example.components;
2 |
3 | /**
4 | * Just another feature of a car.
5 | */
6 | public class Engine {
7 | private final double volume;
8 | private double mileage;
9 | private boolean started;
10 |
11 | public Engine(double volume, double mileage) {
12 | this.volume = volume;
13 | this.mileage = mileage;
14 | }
15 |
16 | public void on() {
17 | started = true;
18 | }
19 |
20 | public void off() {
21 | started = false;
22 | }
23 |
24 | public boolean isStarted() {
25 | return started;
26 | }
27 |
28 | public void go(double mileage) {
29 | if (started) {
30 | this.mileage += mileage;
31 | } else {
32 | System.err.println("Cannot go(), you must start engine first!");
33 | }
34 | }
35 |
36 | public double getVolume() {
37 | return volume;
38 | }
39 |
40 | public double getMileage() {
41 | return mileage;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/strategy/example/order/Order.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.strategy.example.order;
2 |
3 | import refactoring_guru.strategy.example.strategies.PayStrategy;
4 |
5 | /**
6 | * Order class. Doesn't know the concrete payment method (strategy) user has
7 | * picked. It uses common strategy interface to delegate collecting payment data
8 | * to strategy object. It can be used to save order to database.
9 | */
10 | public class Order {
11 | private int totalCost = 0;
12 | private boolean isClosed = false;
13 |
14 | public void processOrder(PayStrategy strategy) {
15 | strategy.collectPaymentDetails();
16 | // Here we could collect and store payment data from the strategy.
17 | }
18 |
19 | public void setTotalCost(int cost) {
20 | this.totalCost += cost;
21 | }
22 |
23 | public int getTotalCost() {
24 | return totalCost;
25 | }
26 |
27 | public boolean isClosed() {
28 | return isClosed;
29 | }
30 |
31 | public void setClosed() {
32 | isClosed = true;
33 | }
34 | }
35 |
36 |
--------------------------------------------------------------------------------
/courses/guru/js/patterns/memento/caretaker.js:
--------------------------------------------------------------------------------
1 | // doesn't depend on Memento
2 | // doesn't have access to Originator state stored in Memento
3 | // it works with all mementos via Memento interface
4 | class Caretaker {
5 | #mementos = [];
6 | #originator = null;
7 |
8 | constructor(originator) {
9 | this.#originator = originator;
10 | }
11 |
12 | // save current memento state
13 | backup() {
14 | console.log('\nCaretaker: saving Originator state...');
15 | this.#mementos.push(this.#originator.save());
16 | }
17 |
18 | // restore memento to previous state
19 | undo() {
20 | if (!this.#mementos.length) {
21 | return;
22 | }
23 | const memento = this.#mementos.pop();
24 | console.log(`Caretaker: restoring state to: ${memento.getName()}`);
25 | this.#originator.restore(memento);
26 | }
27 |
28 | // list all saved mementos
29 | showHistory() {
30 | console.log('Caretaker: list of mementos:');
31 | this.#mementos.forEach((memento) => {
32 | console.log(memento.getName());
33 | });
34 | }
35 | }
36 |
37 | export { Caretaker };
38 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/facade/example/facade/VideoConversionFacade.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.facade.example.facade;
2 |
3 | import refactoring_guru.facade.example.some_complex_media_library.*;
4 |
5 | import java.io.File;
6 |
7 | public class VideoConversionFacade {
8 | public File convertVideo(String fileName, String format) {
9 | System.out.println("VideoConversionFacade: conversion started.");
10 | VideoFile file = new VideoFile(fileName);
11 | Codec sourceCodec = CodecFactory.extract(file);
12 | Codec destinationCodec;
13 | if (format.equals("mp4")) {
14 | destinationCodec = new OggCompressionCodec();
15 | } else {
16 | destinationCodec = new MPEG4CompressionCodec();
17 | }
18 | VideoFile buffer = BitrateReader.read(file, sourceCodec);
19 | VideoFile intermediateResult = BitrateReader.convert(buffer, destinationCodec);
20 | File result = (new AudioMixer()).fix(intermediateResult);
21 | System.out.println("VideoConversionFacade: conversion completed.");
22 | return result;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/decorator/example/decorators/EncryptionDecorator.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.decorator.example.decorators;
2 |
3 | import java.util.Base64;
4 |
5 | public class EncryptionDecorator extends DataSourceDecorator {
6 |
7 | public EncryptionDecorator(DataSource source) {
8 | super(source);
9 | }
10 |
11 | @Override
12 | public void writeData(String data) {
13 | super.writeData(encode(data));
14 | }
15 |
16 | @Override
17 | public String readData() {
18 | return decode(super.readData());
19 | }
20 |
21 | private String encode(String data) {
22 | byte[] result = data.getBytes();
23 | for (int i = 0; i < result.length; i++) {
24 | result[i] += (byte) 1;
25 | }
26 | return Base64.getEncoder().encodeToString(result);
27 | }
28 |
29 | private String decode(String data) {
30 | byte[] result = Base64.getDecoder().decode(data);
31 | for (int i = 0; i < result.length; i++) {
32 | result[i] -= (byte) 1;
33 | }
34 | return new String(result);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/decorator/example/decorators/FileDataSource.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.decorator.example.decorators;
2 |
3 | import java.io.*;
4 |
5 | public class FileDataSource implements DataSource {
6 | private String name;
7 |
8 | public FileDataSource(String name) {
9 | this.name = name;
10 | }
11 |
12 | @Override
13 | public void writeData(String data) {
14 | File file = new File(name);
15 | try (OutputStream fos = new FileOutputStream(file)) {
16 | fos.write(data.getBytes(), 0, data.length());
17 | } catch (IOException ex) {
18 | System.out.println(ex.getMessage());
19 | }
20 | }
21 |
22 | @Override
23 | public String readData() {
24 | char[] buffer = null;
25 | File file = new File(name);
26 | try (FileReader reader = new FileReader(file)) {
27 | buffer = new char[(int) file.length()];
28 | reader.read(buffer);
29 | } catch (IOException ex) {
30 | System.out.println(ex.getMessage());
31 | }
32 | return new String(buffer);
33 | }
34 | }
35 |
36 |
--------------------------------------------------------------------------------
/courses/guru/js/examples/composite.js:
--------------------------------------------------------------------------------
1 | import { ComponentLeaf, ComponentComposite } from '../patterns/composite';
2 |
3 | // client code works with all (simple and both) components via base interface
4 | function clientCode(component) {
5 | console.log(`RESULT: ${component.operation()}`);
6 | }
7 |
8 | /* --- simple component --- */
9 | const leaf = new ComponentLeaf();
10 |
11 | console.log('Client: Simple component:');
12 | clientCode(leaf);
13 |
14 | /* --- composite component --- */
15 | // make "root" component
16 | const tree = new ComponentComposite();
17 | // make one composite component
18 | const branch1 = new ComponentComposite();
19 | // add some simple components to this composite component
20 | branch1.add(new ComponentLeaf());
21 | branch1.add(new ComponentLeaf());
22 |
23 | // make another composite component
24 | const branch2 = new ComponentComposite();
25 | // add some simple component to another composite component
26 | branch2.add(new ComponentLeaf());
27 |
28 | // add composite components to "root" component
29 | tree.add(branch1);
30 | tree.add(branch2);
31 |
32 | console.log('Client: Composite component:');
33 | clientCode(tree);
34 |
--------------------------------------------------------------------------------
/courses/guru/php/src/RefactoringGuru/Memento/Structural/Output.txt:
--------------------------------------------------------------------------------
1 | Originator: My initial state is: Super-duper-super-puper-super.
2 |
3 | Caretaker: Saving Originator's state...
4 | Originator: I'm doing something important.
5 | Originator: and my state has changed to: srGIngezAEboNPDjBkuvymJKUtMSFX
6 |
7 | Caretaker: Saving Originator's state...
8 | Originator: I'm doing something important.
9 | Originator: and my state has changed to: UwCZQaHJOiERLlchyVuMbXNtpqTgWF
10 |
11 | Caretaker: Saving Originator's state...
12 | Originator: I'm doing something important.
13 | Originator: and my state has changed to: incqsdoJXkbDUuVOvRFYyKBgfzwZCQ
14 |
15 | Caretaker: Here's the list of mementos:
16 | 2018-06-04 14:50:39 / (Super-dup...)
17 | 2018-06-04 14:50:39 / (srGIngezA...)
18 | 2018-06-04 14:50:39 / (UwCZQaHJO...)
19 |
20 | Client: Now, let's rollback!
21 |
22 | Caretaker: Restoring state to: 2018-06-04 14:50:39 / (UwCZQaHJO...)
23 | Originator: My state has changed to: UwCZQaHJOiERLlchyVuMbXNtpqTgWF
24 |
25 | Client: Once more!
26 |
27 | Caretaker: Restoring state to: 2018-06-04 14:50:39 / (srGIngezA...)
28 | Originator: My state has changed to: srGIngezAEboNPDjBkuvymJKUtMSFX
29 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/singleton/example/thread_safe/DemoMultiThread.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.singleton.example.thread_safe;
2 |
3 | public class DemoMultiThread {
4 | public static void main(String[] args) {
5 | System.out.println("If you see the same value, then singleton was reused (yay!)" + "\n" +
6 | "If you see different values, then 2 singletons were created (booo!!)" + "\n\n" +
7 | "RESULT:" + "\n");
8 | Thread threadFoo = new Thread(new ThreadFoo());
9 | Thread threadBar = new Thread(new ThreadBar());
10 | threadFoo.start();
11 | threadBar.start();
12 | }
13 |
14 | static class ThreadFoo implements Runnable {
15 | @Override
16 | public void run() {
17 | Singleton singleton = Singleton.getInstance("FOO");
18 | System.out.println(singleton.value);
19 | }
20 | }
21 |
22 | static class ThreadBar implements Runnable {
23 | @Override
24 | public void run() {
25 | Singleton singleton = Singleton.getInstance("BAR");
26 | System.out.println(singleton.value);
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/singleton/example/non_thread_safe/DemoMultiThread.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.singleton.example.non_thread_safe;
2 |
3 | public class DemoMultiThread {
4 | public static void main(String[] args) {
5 | System.out.println("If you see the same value, then singleton was reused (yay!)" + "\n" +
6 | "If you see different values, then 2 singletons were created (booo!!)" + "\n\n" +
7 | "RESULT:" + "\n");
8 | Thread threadFoo = new Thread(new ThreadFoo());
9 | Thread threadBar = new Thread(new ThreadBar());
10 | threadFoo.start();
11 | threadBar.start();
12 | }
13 |
14 | static class ThreadFoo implements Runnable {
15 | @Override
16 | public void run() {
17 | Singleton singleton = Singleton.getInstance("FOO");
18 | System.out.println(singleton.value);
19 | }
20 | }
21 |
22 | static class ThreadBar implements Runnable {
23 | @Override
24 | public void run() {
25 | Singleton singleton = Singleton.getInstance("BAR");
26 | System.out.println(singleton.value);
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/courses/guru/c#/RefactoringGuru.DesignPatterns.Memento.Structural/Output.txt:
--------------------------------------------------------------------------------
1 | Originator: My initial state is: Super-duper-super-puper-super.
2 |
3 | Caretaker: Saving Originator's state...
4 | Originator: I'm doing something important.
5 | Originator: and my state has changed to: oGyQIIatlDDWNgYYqJATTmdwnnGZQj
6 |
7 | Caretaker: Saving Originator's state...
8 | Originator: I'm doing something important.
9 | Originator: and my state has changed to: jBtMDDWogzzRJbTTmEwOOhZrjjBULe
10 |
11 | Caretaker: Saving Originator's state...
12 | Originator: I'm doing something important.
13 | Originator: and my state has changed to: exoHyyRkbuuNEXOhhArKccUmexPPHZ
14 |
15 | Caretaker: Here's the list of mementos:
16 | 12.06.2018 15:52:45 / (Super-dup...)
17 | 12.06.2018 15:52:46 / (oGyQIIatl...)
18 | 12.06.2018 15:52:46 / (jBtMDDWog...)
19 |
20 | Client: Now, let's rollback!
21 |
22 | Caretaker: Restoring state to: 12.06.2018 15:52:46 / (jBtMDDWog...)
23 | Originator: My state has changed to: jBtMDDWogzzRJbTTmEwOOhZrjjBULe
24 |
25 | Client: Once more!
26 |
27 | Caretaker: Restoring state to: 12.06.2018 15:52:46 / (oGyQIIatl...)
28 | Originator: My state has changed to: oGyQIIatlDDWNgYYqJATTmdwnnGZQj
--------------------------------------------------------------------------------
/courses/guru/js/patterns/observer/subjects/subject1.js:
--------------------------------------------------------------------------------
1 | // manage subscribers
2 | class Subject1 {
3 | // Subject state
4 | state = null;
5 |
6 | // list of subscribers
7 | #observers = [];
8 |
9 | // attach Observer to Subject
10 | attach(observer) {
11 | console.log('Subject1: attached to observer.');
12 | this.#observers.push(observer);
13 | }
14 |
15 | // detach Observer from Subject
16 | detach(observer) {
17 | const observerIndex = this.#observers.indexOf(observer);
18 | this.#observers.splice(observerIndex, 1);
19 | console.log('Subject1: detached observer.');
20 | }
21 |
22 | // notify all Observers about event
23 | notify() {
24 | console.log('Subject1: notifying observers...');
25 | this.#observers.forEach((observer) => {
26 | observer.update(this);
27 | });
28 | }
29 |
30 | // some business logic that triggers notification method when smth is happened
31 | someBusinessLogic() {
32 | console.log('\nSubject1: doing some business logic.');
33 | this.state = Math.floor(Math.random() * (10 + 1));
34 |
35 | console.log(`Subject1: state changed to: ${this.state}`);
36 | this.notify();
37 | }
38 | }
39 |
40 | export { Subject1 };
41 |
--------------------------------------------------------------------------------
/courses/guru/java/src/refactoring_guru/memento/example/Demo.java:
--------------------------------------------------------------------------------
1 | package refactoring_guru.memento.example;
2 |
3 | import refactoring_guru.memento.example.editor.Editor;
4 | import refactoring_guru.memento.example.shapes.Circle;
5 | import refactoring_guru.memento.example.shapes.CompoundShape;
6 | import refactoring_guru.memento.example.shapes.Dot;
7 | import refactoring_guru.memento.example.shapes.Rectangle;
8 |
9 | import java.awt.*;
10 |
11 | public class Demo {
12 | public static void main(String[] args) {
13 | Editor editor = new Editor();
14 | editor.loadShapes(
15 | new Circle(10, 10, 10, Color.BLUE),
16 |
17 | new CompoundShape(
18 | new Circle(110, 110, 50, Color.RED),
19 | new Dot(160, 160, Color.RED)
20 | ),
21 |
22 | new CompoundShape(
23 | new Rectangle(250, 250, 100, 100, Color.GREEN),
24 | new Dot(240, 240, Color.GREEN),
25 | new Dot(240, 360, Color.GREEN),
26 | new Dot(360, 360, Color.GREEN),
27 | new Dot(360, 240, Color.GREEN)
28 | )
29 | );
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/courses/guru/js/examples/singleton.js:
--------------------------------------------------------------------------------
1 | import { Singleton } from '../patterns/singleton';
2 |
3 | // create object #1 with new
4 | const singleton1 = new Singleton();
5 | console.log(singleton1);
6 |
7 | // create object #2 with new
8 | const singleton2 = new Singleton();
9 | console.log(singleton2);
10 |
11 | // check: are they totally equal?
12 | // must be true
13 | console.log(singleton1 === singleton2);
14 |
15 | // create object #3 with method
16 | const singleton3 = Singleton.getInstance();
17 | console.log(singleton3);
18 |
19 | // create object #4 with method
20 | const singleton4 = Singleton.getInstance();
21 | console.log(singleton4);
22 |
23 | // check: are they totally equal?
24 | // must be true
25 | console.log(singleton3 === singleton4);
26 |
27 | // check: is object instance of Singleton
28 | // must be true
29 | console.log(singleton1 instanceof Singleton);
30 | console.log(singleton3 instanceof Singleton);
31 |
32 | // read object property
33 | // must return property value
34 | console.log(singleton1.password);
35 |
36 | // check: direct access to instance
37 | // must be undefined
38 | console.log(Singleton.instance);
39 |
40 | // check: direct access to private data
41 | // must be undefined
42 | console.log(Singleton.privateObject);
43 |
--------------------------------------------------------------------------------