Skip to content

Instantly share code, notes, and snippets.

@athulmurali
Last active May 26, 2019 16:41
Show Gist options
  • Save athulmurali/710790552c1a07c4d44b98fa77959fcf to your computer and use it in GitHub Desktop.
Save athulmurali/710790552c1a07c4d44b98fa77959fcf to your computer and use it in GitHub Desktop.
Singleton Pattern
import coursesData from './courses'
function CourseService() {
let courses = coursesData;
return {
addCourse: (newCourse) => {
courses.push(newCourse);
},
deleteCourse: (id) => {
courses = courses.filter(course => course.id !== id)
},
findAllCourses: () => {
return courses
}
}
}
export default CourseService();
import CourseService from './Closure'
import CourseService1 from './WrapperSingleton'
const Comp=()=>{
console.log(CourseService.findAllCourses())
return <div></div>
}
// Using a wrapper class
class CourseService {
constructor(){
this.instance = null;
this.courses=[];
}
addCourse=(newCourse)=>{
this.courses.push(newCourse);
}
deleteCourse=(id)=>{
this.courses = this.courses.filter(course=>course.id !== id)
}
}
class SingleTon{
instance = null;
static getInstance(){
if (this.courseService)
return this.courseService;
else
this.courseService= new CourseService();
return this.courseService;
}
}
export default SingleTon.getInstance();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment