fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,70 @@
---
title: Builder
---
The builder is a design pattern that could abstract and decouple the creation of a very complex object.
## Builder in Python
Here is an example of Builder Pattern implementation in Python3.
```python
# Builder
class CourseBuilder(object):
def __init__(self, teacher):
self.teacher = teacher
def build_course(self):
self.teacher.provide_homework()
self.teacher.provide_exam()
return self.teacher.course
# Teacher
class Teacher(object):
def __init__(self, name=None):
self.name = name
self.course = Course()
def provide_homework(self):
raise NotImplementedError
def provide_exam(self):
raise NotImplementedError
class MathTeacher(Teacher):
def provide_homework(self):
self.course.homework = 'This is Math homework provided by {}.'.format(self.name)
def provide_exam(self):
self.course.exam = 'This is Math exam tested by {}.'.format(self.name)
class HistoryTeacher(Teacher):
def provide_homework(self):
self.course.homework = 'This is History homework provided by {}.'.format(self.name)
def provide_exam(self):
self.course.exam = 'This is History exam tested by {}.'.format(self.name)
# Target objects to be produced
class Course(object):
def __init__(self):
self.homework = None
self.exam = None
def __str__(self):
return 'Homework: {}\nExam: {}\n'.format(self.homework, self.exam)
math_course = CourseBuilder(MathTeacher('Harry')).build_course()
print(math_course)
>>> Homework: This is Math homework provided by Harry.
>>> Exam: This is Math exam tested by Harry.
history_course = CourseBuilder(HistoryTeacher('Potter')).build_course()
print(history_course)
>>> Homework: This is History homework provided by Potter.
>>> Exam: This is History exam tested by Potter.
```

View File

@ -0,0 +1,40 @@
---
title: Decorator
---
The decorator is a design pattern that could modify or enhance the interface of a class.
## Decorator in Python3
Here is an example of Decorator implementation in Python3.
```python
class MyText(object):
def __init__(self, text=''):
self.text = text
def __str__(self):
return 'This is {}'.format(self.text)
class BracketDecorator(object):
def __init__(self, decoratee):
self._decoratee = decoratee
def __str__(self):
return '({})'.format(self._decoratee)
class QuoteDecorator(object):
def __init__(self, decoratee):
self._decoratee = decoratee
def __str__(self):
return '\"{}\"'.format(self._decoratee)
print(BracketDecorator(MyText('apple')))
>>> (This is apple)
print(QuoteDecorator(MyText('banana')))
>>> "This is banana"
```

View File

@ -0,0 +1,15 @@
---
title: Factory Method
---
## Factory Method
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/machine-learning/monte-carlo/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -0,0 +1,103 @@
---
title: Factory
---
The factory is a design pattern which aims to reduce the dependencies between classes instantiating (creating) objects and the objects themselves, by creating a "factory" class which handles the creation of classes. By doing this, we allow can allow subclasses to redefine which class to instantiate, and group potentially complex creation logic into a single interface.
Programmers use factory design patterns to because it allows them to create instances of objects which implement a common interface, without necessarily knowing beforehand the exact concrete class (implementation) being used. A common situation in which this is useful is when a parent class is relying on it's children classes to specify the type of object it should be instantiating. It is also useful when the creation of an object is complex, as it allows the programmer to group the code into a single class and reduce duplication.
## Using the Factory Pattern in Java
To use the factory design pattern, you first need to have a interface - an object with class and variable names, but no definitions. For example, here we have a Java interface for animals.
```
public interface Animal {
void talk();
}
```
We now need to have "concrete classes" - classes which implement our interface and define the associated functions/ variables.
```
public class Dog implements Animal {
@Override
public void talk() {
System.out.println("Woof");
}
}
```
```
public class Cat implements Animal {
@Override
public void talk() {
System.out.println("Meow!");
}
}
```
We now define our "AnimalFactory" - the class which will handle the creation of these classes.
```
public class AnimalFactory {
public Animal getAnimal(String animalType) {
if (animalType.equals("dog")) {
return new Dog();
} else if (animalType.equals("cat")) {
return new Cat();
}
return null;
}
}
```
Now when we want to create a new Cat object, instead of saying something like ``` Cat cat = new Cat(); ```, we use the factory class that we have defined. For example:
```
AnimalFactory animalFactory = new AnimalFactory();
Animal cat = animalFactory.getAnimal("cat");
cat.talk();
```
Here we can see that the class with this instance of "Cat" doesn't really know which animal it has. But this doesn't matter - because all the classes the factory creates are concrete classes of the same interface, the parent class doesn't need to know the exact class it is using.
## Factory in Python3
We can implement a Factory easily with static methods.
```python
class Drink(object):
def __init__(self, name, price=None):
self.name = name
self.price = price
class Tea(Drink):
def __str__(self):
return 'This is tea: {} in ${}'.format(self.name, self.price)
class Milk(Drink):
def __str__(self):
return 'This is milk: {} in ${}'.format(self.name, self.price)
class DrinkFactory(object):
@staticmethod
def generate(drink_type=None, *args, **kwargs):
if drink_type == 'tea':
return Tea(*args, **kwargs)
elif drink_type == 'milk':
return Milk(*args, **kwargs)
raise NotImplementedError("{} drink do not exist.".format(drink_type))
# Testing
black_tea = DrinkFactory.generate('tea', 'Black Tea', price=4.39)
whole_milk = DrinkFactory.generate('milk', 'Whole Milk', price=5.49)
print(black_tea)
print(whole_milk)
```

View File

@ -0,0 +1,65 @@
---
title: Finite State Machine
---
The finite state machine (FSM) is a software design pattern where a given model transitions to other behavioral states through external input.
## Finite State Machine
A FSM is defined by its **states**, it's **initial state** and the **transitions**.
The power of FSM comes from the ability to clearly define different *behaviors* in different conditions. Usually FSM is used with looping behavioral scripts which constantly evaluate the current situation in a loop or with events.
To help form an image of how this might be applied, a coffee machine will be used as an example of a finite state machine. We will also cover a state diagram to visualise the FSM and provide coding examples.
### State Diagram
![Coffee machine finite state machine diagram](https://raw.githubusercontent.com/arunma/blogimages/master/AkkaFSM/CoffeeMachineFSM.png)
This diagram shows three possible states for the coffee machine:
- Open
- ReadyToBuy
- PoweredOff
The lines between these states show which transitions are possible between states and in which direction. These transitions have conditions for when the FSM needs to change between states.
- StartUpMachine
From the PoweredOff state to the Open state the machine has to start up. This is done manually in this case.
- deposit >= cost of coffee
The FSM evaluates the amount of deposited cash either in a loop or when the amount changes (recommended in this case)
If you deposit enough cash into the coffee machine, the FSM will go from 'Open' to 'ReadyToBuy'.
- ShutdownMachine
The machine will automatically go from Open to PoweredOff through the ShutDownMachine method if the condition 'no more coffees left' is met.
- DispenseCoffee
In the ReadyToBuy state the user can buy a coffee whereafter it will be brewed and dispensed. The condition is when the BuyCoffee event (!Link to observer pattern!) fires. (not shown in diagram)
- CancelCoffee
If the user opts to cancel, the machine will go from ReadyToBuy to Open.
- ShutDownMachine
The machine will go to PoweredOff state
### States
In every state there is defined behavior which will only be executed when the object is in that state. For instance, during PoweredOff the coffee machine won't brew coffee before it's powered on, during the Open state it will wait either until there's enough cash inserted, until the power down command is given, or until it runs out of coffee. During this Open state it can do routines such as cleaning which won't happen in other states.
### Initial State
Every FSM has an initial state, this means which state it starts in when it is created and has to be defined when constructed or instantiated. Of course it's possible to directly change state if conditions are met.
### Transitions
Every state either constantly evaluates if it should transition to another state or will transition to another state based on a triggered event.
## DFA and NFA
There are two types of finite automaton, Deterministic (DFA) and Nondeterministic (NFA). Both of them accept regular languages and operate more or less in the same way described above however with some differences.
A DFA accepts or rejects a string of symbols and only produces one unique computation or automaton for each input string. <i>Deterministic</i> refers to the uniquness of the computation.
A Finite State Machine is called a DFA if it obeys the following rules:
1. Each of its transitions is <i>uniquely</i> determined by its source state and input symbol
2. Reading an input symbol is required for each state transition.
An NFA does not need to obey these restrictions, meaning that each DFA is also an NFA.
And since they both only recognize regular languages, each NFA can be converted into an equivalent DFA using the powerset construction algorithm.
So what sort of rules can we expect to find in NFAs but not DFAs ?
1. An NFA can have an <i>empty string</i> transition (generally denoted by an epsilon). Meaning that when at a certain state with an epsilon for a transition rule, the machine can transition to the next state without reading an input symbol
2. In an NFA, each pair of state and transition symbol can have multiple destination states as opposed to the unique destinations of pairs in DFAs
3. Each pair of state and transition symbol produces a 'branch' of computation for each of its possible destination creating some sort of a multithreaded system.
4. A DFA will reject the input string if it lands on any state other than the acceptance state. In an NFA, we only need one 'branch' to land on an acceptance state in order to accept the string.

View File

@ -0,0 +1,48 @@
---
title: Design Patterns
---
## Design Patterns
Programmers and software architects use design patterns to solve **common, recurring problems** in software architecture. The patterns provide a language-agnostic approach to **object-oriented programming** that helps developers follow principles of good application design.
### Why Design Patterns?
Developing by design patterns offer several advantages:
* It's easier to follow good programming principles such as the **<a href='https://www.youtube.com/watch?v=XzdhzyAukMM' target='_blank' rel='nofollow'>SOLID</a> <a href='https://medium.com/@cramirez92/s-o-l-i-d-the-first-5-priciples-of-object-oriented-design-with-javascript-790f6ac9b9fa' target='_blank' rel='nofollow'>principles</a>.**
* It keeps code chunks smaller so code is easier to **test** and **debug**
* It helps keep code loosely coupled so code is easier to **re-use** and **update** for new applications
* It makes code easier to **understand**, so new contributors can **ramp up quickly**
Using design patterns incurs some trade-offs, and developers new to the practice should remember the following:
* There are **no silver bullets** in programming, and design patterns are not an exception
* Design patterns add a **layer of abstraction** to code which increases initial design and development effort
* Over-use of design patterns or forcing them to fit makes code **harder** to understand
### Language Support
Design patterns originated from the world of statically-typed languages like C++, Java, and C#. Most resources about development by design pattern are based in one of these languages.
Nonetheless, design patterns are just that: patterns. They are **not implementations**, like classes or interfaces, and are **not constrained to any one language**.
When learning design patterns within a dynamic language, if particular patterns seem needlessly complex or counter-intuitive, recall their origins. Developers in dynamic languages can still use and benefit from following design patterns, although more research may be required to fully understand them.
### Uses
Design patterns are excellent at solving foundational coding problems in a simple and repeatable fashion. Broadly, they fall into three categories:
* **Creational** patterns describe how to create new objects
* **Structural** patterns describe how to compose objects out of other objects
* **Behavioral** patterns describe how objects communicate with each other
These tasks can all be performed without design patterns, but design patterns **reduce the risk** that you will violate good practices and create code that is hard to maintain.
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
* Kamran Ahmed's <a href='https://github.com/kamranahmedse/design-patterns-for-humans' target='_blank' rel='nofollow'>Design Patterns for Humans</a> is an excellent introduction to the specific patterns
* <a href='https://en.wikipedia.org/wiki/Design_Patterns' target='_blank' rel='nofollow'>Design Patterns</a> is the book that started this practice
* Martin Fowler's <a href='https://martinfowler.com/eaaCatalog/' target='_blank' rel='nofollow'>Patterns of Enterprise Application Architecture</a> provide a suite of more sophisticated patterns for enterprise applications
* Sourcemaking provides an <a href='https://sourcemaking.com/design_patterns' target='_blank' rel='nofollow'>online resource</a> with additional examples and information about design patterns

View File

@ -0,0 +1,12 @@
---
title: Observer pattern
---
The Observer pattern offers a subscription model in which objects subscribe to an event and get notified when the event occurs.
## Observer pattern
This pattern is the basis of event-driven programming. In Front End Development this is an essential pattern to sturdily scale your application logic. In this pattern, you make a difference between the **subject** and the **observers**. The subjects are the events themselves such as a _click_, a _keypress_ or a signal from the server. All subscribed **observers** are notified when a subject changes state (when an event fires). For more information on events read here [Evenet Driven Programming](https://www.technologyuk.net/software-development/designing-software/event-driven-programming.shtml)
### Subscribing
The advantage of this pattern is having a collection of subscribed objects that will respond to an event instead of calling a function on every object that should be notified. Another advantage is that observers are subscribed through an interface, which allows changes to the event function to be only within the function.
## Other resources
A code example & more at [Observer Design Pattern](http://www.dofactory.com/javascript/observer-design-pattern)

View File

@ -0,0 +1,152 @@
---
title: Singleton
---
The singleton is a design pattern that restricts the instantiation of a class to one object. It is useful when you want to give only one object the ability to coordinate actions across your application.
## Singleton in Android
Singleton is a design pattern often used in Android. It is easily misused and so can cause app to be hard to maintain. It is useful in Android because they live across fragments, activities, and rotations.
- Singletons are often used in Android to store temporary data
- They allow the application to have one owner of the data and provides an easy way to pass data between controller classes
- Singletons are destroyed when Android removes your app from memory
- Singletons can make it difficult to unit test your app
```java
public class DataStore {
private static DataStore sDataStore;
private List<Data> mData;
public static DataStore get(Context context) {
if (sDataStore == null) {
sDataStore = new DataStore(context);
}
return sDataStore;
}
// Make constructor private to prevent other classes from creating a DataStore instance
private DataStore(Context context) {
mData = new ArrayList<>();
}
// The only way for other classes to get data from DataStore
public List<Data> getData() {
return mData;
}
}
```
## Singleton in PHP
> A private constructor is used to prevent the direct creation of objects from the class.
> The only way to create an instance from the class is by using a static method that creates the object only if it wasn't already created.
```php
Class Singleton {
// Hold the class instance
private static $instance = null;
/**
* The constructor is private
* it is ensure the class can be initialized only from itself
*/
private function __construct(){}
/**
* Return the singleton instance of this class
*
* @return Singleton
*/
public static function getInstance()
{
if (self::$instance == null)
{
self::$instance = new Singleton();
}
return self::$instance;
}
}
$obj1 = Singleton::getInstance();
$obj2 = Singleton::getInstance();
```
## Singleton in C#
The most elegant, simple and highly performant version of the pattern using [System.Lazy\<T\>](http://msdn.microsoft.com/en-us/library/dd642331.aspx) type from .NET 4.0 or higher.
```csharp
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
```
## Singleton in Python3
We can use metaclass to implement Singleton in Python3.
```python
class Singleton(type):
# Mapping from a class to its singleton instance
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in Singleton._instances:
Singleton._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return Singleton._instances[cls]
class MyClass(metaclass=Singleton):
pass
```
### Testing
```python
obj_0 = MyClass()
obj_1 = MyClass()
In [2]: obj_0
Out[2]: <__main__.MyClass at 0x111130da0>
In [3]: obj_1
Out[3]: <__main__.MyClass at 0x111130da0>
```
## Singleton in iOS
```Swift4
class Singleton {
static let sharedInstance = Singleton()
init() {
print("Singleton has been initialized")
}
//write your functions here
func sampleFunction() {
}
}
//Uses
Singleton.sharedInstance.sampleFunction()
```
This simple code is all there to implement a singleton design pattern in iOS using Swift. We put `static` because it is a type property, and its functionality is to create only one instance of an object and prevents its methods from being overridden. Using `let` will guarantee that sharedInstance's value will not change.
An important thing to note is that `static` properties and methods are lazy initialize by default meaning that it will not be instantiated until it is being called, therefore it provides some optimization.
## More Information
For more information, visit the following links:
- [MSDN: Implementing Singleton in C#](https://msdn.microsoft.com/en-us/library/ff650316.aspx)
- [C# in Depth. Implementing the Singleton Pattern in C#](http://csharpindepth.com/Articles/General/Singleton.aspx)