diff --git a/src/admin.type.ts b/src/admin.type.ts new file mode 100644 index 0000000..bce8507 --- /dev/null +++ b/src/admin.type.ts @@ -0,0 +1,9 @@ +import Admin from './admin'; +import User from './user'; +import UserFactory from './user.factory'; + +export default class AdminType implements UserFactory { + create(pseudo: string): User { + return new Admin(pseudo); + } +} diff --git a/src/application.ts b/src/application.ts index 08161e4..d51b528 100644 --- a/src/application.ts +++ b/src/application.ts @@ -1,11 +1,11 @@ -import Admin from './admin'; +import UserFactoryProvider from './user.factory.provider'; import Article from './article'; import ArticleJsonFactory from './article.json.factory'; import ArticleRepository from './article.repository'; -import Contributor from './contributor'; import Database from './database'; import { UserType } from './types'; import User from './user'; +import UserFactory from './user.factory'; export default class Application { run(): number { @@ -16,14 +16,9 @@ export default class Application { const userPseudo = 'pierre'; const userType: UserType = 'admin'; - const user: User = (() => { - switch (userType as UserType) { - case 'admin': - return new Admin(userPseudo); - case 'contributor': - return new Contributor(userPseudo); - } - })(); + const userFactory: UserFactory = + UserFactoryProvider.provideFromUserType(userType); + const user: User = userFactory.create(userPseudo); const article = new Article(user, 'Mon premier article'); diff --git a/src/contributor.type.ts b/src/contributor.type.ts new file mode 100644 index 0000000..ece5c1e --- /dev/null +++ b/src/contributor.type.ts @@ -0,0 +1,9 @@ +import Contributor from './contributor'; +import User from './user'; +import UserFactory from './user.factory'; + +export default class ContributorType implements UserFactory { + create(pseudo: string): User { + return new Contributor(pseudo); + } +} diff --git a/src/user.factory.provider.ts b/src/user.factory.provider.ts new file mode 100644 index 0000000..ba89a59 --- /dev/null +++ b/src/user.factory.provider.ts @@ -0,0 +1,15 @@ +import AdminType from './admin.type'; +import ContributorType from './contributor.type'; +import { UserType } from './types'; +import UserFactory from './user.factory'; + +export default abstract class UserFactoryProvider { + static provideFromUserType(userType: UserType): UserFactory { + if (userType === 'admin') { + return new AdminType(); + } else if (userType === 'contributor') { + return new ContributorType(); + } + throw new Error(`"${userType} is not a valid user type"`); + } +} diff --git a/src/user.factory.ts b/src/user.factory.ts new file mode 100644 index 0000000..94628a2 --- /dev/null +++ b/src/user.factory.ts @@ -0,0 +1,5 @@ +import User from './user'; + +export default interface UserFactory { + create(pseudo: string): User; +}