Initial commit

parents
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Ship = void 0;
class Ship {
transfer(country, transferItem) {
console.log(`Груз плывет по морю в ${country}`);
}
}
exports.Ship = Ship;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Truck = void 0;
class Truck {
transfer(country, transferItem) {
console.log(`Груз проехал по суше в страну ${country}`);
}
}
exports.Truck = Truck;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ShipCreator = void 0;
const Ship_1 = require("../transport/Ship");
const TransportCreator_1 = require("./TransportCreator");
class ShipCreator extends TransportCreator_1.TransportCreator {
factoryMethod() {
return new Ship_1.Ship();
}
}
exports.ShipCreator = ShipCreator;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TransportCreator = void 0;
class TransportCreator {
transfer(country, transferItem) {
const transport = this.factoryMethod();
transport.transfer(country, transferItem);
}
}
exports.TransportCreator = TransportCreator;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TruckCreator = void 0;
const Truck_1 = require("../transport/Truck");
const TransportCreator_1 = require("./TransportCreator");
class TruckCreator extends TransportCreator_1.TransportCreator {
factoryMethod() {
return new Truck_1.Truck();
}
}
exports.TruckCreator = TruckCreator;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Ship = void 0;
class Ship {
transfer(country, transferItem) {
console.log(`Груз плывет по морю в ${country}`);
}
}
exports.Ship = Ship;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Truck = void 0;
class Truck {
transfer(country, transferItem) {
console.log(`Груз проехал по суше в страну ${country}`);
}
}
exports.Truck = Truck;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Ship = void 0;
class Ship {
transfer(country, transferItem) {
console.log(`Груз плывет по морю в ${country}`);
}
}
exports.Ship = Ship;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Truck = void 0;
class Truck {
transfer(country, transferItem) {
console.log(`Груз проехал по суше в страну ${country}`);
}
}
exports.Truck = Truck;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Context_1 = require("./strategy-pattern/Context");
const AddStrategy_1 = require("./strategy-pattern/strategy/AddStrategy");
const MultiplyStrategy_1 = require("./strategy-pattern/strategy/MultiplyStrategy");
const SubstractStrategy_1 = require("./strategy-pattern/strategy/SubstractStrategy");
function clientCode(creator) {
let isTruck = true;
const country = "Kazakhstan";
const goods = ["bmw", "zeekr"];
creator.transfer(country, goods);
// if (isTruck) {
// const truck = new Truck();
// truck.transfer(country, goods);
// } else {
// const ship = new Ship();
// ship.transfer(country, goods);
// }
}
// console.log('Запускается реализация для сухопутной перевозки');
// clientCode(new TruckCreator());
// console.log('Запускается реализация для морской перевозки');
// clientCode(new ShipCreator());
// const doc: UserDocument = new UserDocument("admin");
// doc.sendForModeration();
// doc.sendForModeration();
// doc.sendForPublication();
// doc.sendForDraft();
let action = "multiply";
let context = new Context_1.Context();
if (action === "add") {
context.setStrategy(new AddStrategy_1.AddStrategy());
}
else if (action === "subsctract") {
context.setStrategy(new SubstractStrategy_1.SubstractStrategy());
}
else {
context.setStrategy(new MultiplyStrategy_1.MultiplyStrategy());
}
const result = context.execute(5, 3);
console.log(result);
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UserDocument = void 0;
const DraftState_1 = require("./state/DraftState");
class UserDocument {
constructor(user) {
this._currentUser = user;
this.changeState(new DraftState_1.DraftState());
}
changeState(state) {
this._state = state;
this._state.setDocument(this);
}
get currentUser() {
return this._currentUser;
}
sendForDraft() {
this._state.draft();
}
sendForModeration() {
this._state.moderate();
}
sendForPublication() {
this._state.publish();
}
}
exports.UserDocument = UserDocument;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DraftState = void 0;
const ModeratedState_1 = require("./ModeratedState");
const State_1 = require("./State");
class DraftState extends State_1.State {
draft() {
console.log("Документ находится в подготовке");
}
moderate() {
console.log("Документ отправлен на модерацию");
this.document.changeState(new ModeratedState_1.ModeratedState());
}
publish() {
console.log("Документ не прошел модерацию и не может быть опубликован");
}
}
exports.DraftState = DraftState;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModeratedState = void 0;
const DraftState_1 = require("./DraftState");
const PublishedState_1 = require("./PublishedState");
const State_1 = require("./State");
class ModeratedState extends State_1.State {
draft() {
console.log('Документ отправлен на повторную подготовку');
this.document.changeState(new DraftState_1.DraftState());
}
moderate() {
console.log('Документ уже находится в модерации');
}
publish() {
if (this.document.currentUser === "admin") {
console.log('Отправляем документ на публикацию');
this.document.changeState(new PublishedState_1.PublishedState());
}
else {
console.log('У вас нет прав на публикацию');
}
}
}
exports.ModeratedState = ModeratedState;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PublishedState = void 0;
const State_1 = require("./State");
class PublishedState extends State_1.State {
draft() {
console.log("Документ уже опубликован, нет возможности отправить на подготовку");
}
moderate() {
console.log("Документ уже опубликован, нет возможности отправить на модерацию");
}
publish() {
console.log("Документ уже опубликован");
}
}
exports.PublishedState = PublishedState;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.State = void 0;
class State {
setDocument(document) {
this.document = document;
}
}
exports.State = State;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Context = void 0;
class Context {
setStrategy(strategy) {
this._strategy = strategy;
}
execute(a, b) {
return this._strategy.execute(a, b);
}
}
exports.Context = Context;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AddStrategy = void 0;
class AddStrategy {
execute(a, b) {
return a + b;
}
}
exports.AddStrategy = AddStrategy;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MultiplyStrategy = void 0;
class MultiplyStrategy {
execute(a, b) {
return a * b;
}
}
exports.MultiplyStrategy = MultiplyStrategy;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SubstractStrategy = void 0;
class SubstractStrategy {
execute(a, b) {
return a - b;
}
}
exports.SubstractStrategy = SubstractStrategy;
export interface ITransport {
transfer(country: string, transferItem: string[]): void;
}
\ No newline at end of file
import { ITransport } from "../ITransport";
import { Ship } from "../transport/Ship";
import { TransportCreator } from "./TransportCreator";
export class ShipCreator extends TransportCreator {
public factoryMethod(): ITransport {
return new Ship();
}
}
\ No newline at end of file
import { ITransport } from "../ITransport";
export abstract class TransportCreator {
public abstract factoryMethod(): ITransport;
public transfer(country: string, transferItem: string[]) {
const transport = this.factoryMethod();
transport.transfer(country, transferItem);
}
}
\ No newline at end of file
import { ITransport } from "../ITransport";
import { Truck } from "../transport/Truck";
import { TransportCreator } from "./TransportCreator";
export class TruckCreator extends TransportCreator {
public factoryMethod(): ITransport {
return new Truck();
}
}
\ No newline at end of file
import { ITransport } from "../ITransport";
export class Ship implements ITransport {
transfer(country: string, transferItem: string[]): void {
console.log(`Груз плывет по морю в ${country}`);
}
}
\ No newline at end of file
import { ITransport } from "../ITransport";
export class Truck implements ITransport {
transfer(country: string, transferItem: string[]): void {
console.log(`Груз проехал по суше в страну ${country}`);
}
}
\ No newline at end of file
import { ShipCreator } from "./factory-pattern/factory/ShipCreator";
import { TransportCreator } from "./factory-pattern/factory/TransportCreator";
import { TruckCreator } from "./factory-pattern/factory/TruckCreator";
import { UserDocument } from "./state-pattern/UserDocument";
import { Context } from "./strategy-pattern/Context";
import { AddStrategy } from "./strategy-pattern/strategy/AddStrategy";
import { MultiplyStrategy } from "./strategy-pattern/strategy/MultiplyStrategy";
import { SubstractStrategy } from "./strategy-pattern/strategy/SubstractStrategy";
function clientCode(creator: TransportCreator) {
let isTruck = true;
const country = "Kazakhstan";
const goods = ["bmw", "zeekr"];
creator.transfer(country, goods);
// if (isTruck) {
// const truck = new Truck();
// truck.transfer(country, goods);
// } else {
// const ship = new Ship();
// ship.transfer(country, goods);
// }
}
// console.log('Запускается реализация для сухопутной перевозки');
// clientCode(new TruckCreator());
// console.log('Запускается реализация для морской перевозки');
// clientCode(new ShipCreator());
// const doc: UserDocument = new UserDocument("admin");
// doc.sendForModeration();
// doc.sendForModeration();
// doc.sendForPublication();
// doc.sendForDraft();
let action = "add";
let context = new Context();
if (action === "add") {
context.setStrategy(new AddStrategy());
} else if (action === "subsctract") {
context.setStrategy(new SubstractStrategy());
} else {
context.setStrategy(new MultiplyStrategy());
}
const result = context.execute(5, 3);
console.log(result);
import { DraftState } from "./state/DraftState";
import { State } from "./state/State";
export class UserDocument {
private _state!: State;
private _currentUser: string;
constructor(user: string) {
this._currentUser = user;
this.changeState(new DraftState());
}
public changeState(state: State) {
this._state = state;
this._state.setDocument(this);
}
get currentUser(): string {
return this._currentUser;
}
public sendForDraft(): void {
this._state.draft();
}
public sendForModeration(): void {
this._state.moderate();
}
public sendForPublication(): void {
this._state.publish();
}
// public publish() {
// switch(this._state) {
// case 'draft':
// this._state = 'moderation';
// break;
// case 'moderation':
// if (this._currentUser === 'admin') {
// this._state = 'published';
// } else {
// console.log('У вас нет прав');
// }
// break;
// case 'published':
// break;
// }
// }
}
\ No newline at end of file
import { ModeratedState } from "./ModeratedState";
import { State } from "./State";
export class DraftState extends State {
public override draft(): void {
console.log("Документ находится в подготовке");
}
public override moderate(): void {
console.log("Документ отправлен на модерацию");
this.document.changeState(new ModeratedState());
}
public override publish(): void {
console.log("Документ не прошел модерацию и не может быть опубликован");
}
}
import { DraftState } from "./DraftState";
import { PublishedState } from "./PublishedState";
import { State } from "./State";
export class ModeratedState extends State {
public override draft(): void {
console.log('Документ отправлен на повторную подготовку');
this.document.changeState(new DraftState());
}
public override moderate(): void {
console.log('Документ уже находится в модерации');
}
public override publish(): void {
if (this.document.currentUser === "admin") {
console.log('Отправляем документ на публикацию');
this.document.changeState(new PublishedState());
} else {
console.log('У вас нет прав на публикацию');
}
}
}
\ No newline at end of file
import { State } from "./State";
export class PublishedState extends State {
public override draft(): void {
console.log("Документ уже опубликован, нет возможности отправить на подготовку");
}
public override moderate(): void {
console.log("Документ уже опубликован, нет возможности отправить на модерацию");
}
public override publish(): void {
console.log("Документ уже опубликован");
}
}
\ No newline at end of file
import { UserDocument } from "../UserDocument";
export abstract class State {
protected document!: UserDocument;
public setDocument(document: UserDocument): void {
this.document = document;
}
public abstract draft(): void;
public abstract moderate(): void;
public abstract publish(): void;
}
\ No newline at end of file
import { IStrategy } from "./IStrategy";
export class Context {
private _strategy!: IStrategy;
public setStrategy(strategy: IStrategy) {
this._strategy = strategy;
}
execute(a: number, b: number): number {
return this._strategy.execute(a, b);
}
}
\ No newline at end of file
export interface IStrategy {
execute(a: number, b: number): number;
}
\ No newline at end of file
import { IStrategy } from "../IStrategy";
export class AddStrategy implements IStrategy {
execute(a: number, b: number): number {
return a + b;
}
}
\ No newline at end of file
import { IStrategy } from "../IStrategy";
export class MultiplyStrategy implements IStrategy {
execute(a: number, b: number): number {
return a * b;
}
}
\ No newline at end of file
import { IStrategy } from "../IStrategy";
export class SubstractStrategy implements IStrategy {
execute(a: number, b: number): number {
return a - b;
}
}
\ No newline at end of file
{
"include": ["src"],
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "./build", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
"noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment