Designing Factory pattern in line with Solid Design Principles

class DataStructureFactory {

constructor(name) {
this.name = name;
if(name === 'queue') {
this.ds = new Queue();
}
else if(name === 'stack') {
this.ds = new Stack();
}
return this.ds;
}
}
class Stack
{
constructor() {
this.data = [];
}
add(value) {
this.data.push(value);
}
remove() {
this.data.pop();
}
print() {
console.log(this.data);
}
}
class Queue
{
constructor() {
this.first = null;
this.last = null;
}

enqueue(value) {
let newNode = {
value,
next: null
};
if (this.first === null) {
this.first = {
value,
next: null
};
return this.last = this.first;
}
this.last.next = newNode;
this.last = newNode;
}
dequeue() {
this.first = this.first.next;
}
print() {
let values = []
let currentNode = this.first;

while (currentNode) {
values.push(currentNode.value);
currentNode = currentNode.next;
}
console.log(values);
}
}
const queue = new DataStructureFactory('queue');
const stack = new DataStructureFactory('stack');
// populating and unpopulating data structure with some valuesqueue.enqueue(5);
queue.enqueue(51);
queue.enqueue(70);
queue.dequeue();
stack.add(10);
stack.add(15);
stack.remove();
//retrieving the data structure valuesstack.print();
queue.print();
UML representation of DataStructure Factory pattern
class DataStructureFactory {

initStack() {
return new Stack();
}
initQueue() {
return new Queue();
}
}
class Stack
{
constructor() {
this.data = [];
}
add(value) {
this.data.push(value);
}
remove() {
this.data.pop();
}
print() {
console.log(this.data);
}
}
class Queue
{
constructor() {
this.first = null;
this.last = null;
}
enqueue(value) {
let newNode = {
value,
next: null
};
if (this.first === null) {
this.first = {
value,
next: null
};
return this.last = this.first;
}
this.last.next = newNode;
this.last = newNode;
}
dequeue() {
this.first = this.first.next;
}
print() {
let values = []
let currentNode = this.first;
while (currentNode) {
values.push(currentNode.value);
currentNode = currentNode.next;
}
console.log(values);
}
}
const queue = new DataStructureFactory().initQueue();
const stack = new DataStructureFactory().initStack();
// populating and unpopulating data structure with some valuesqueue.enqueue(5);
queue.enqueue(51);
queue.enqueue(70);
queue.dequeue();
stack.add(10);
stack.add(15);
stack.remove();
//retrieving the data structure valuesstack.print();
queue.print();

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store