You are on page 1of 51

Creational Design Patterns

Creational design patterns concern the process of object creation. These are
the patterns comes under creational design patterns.

 Abstract Factory pattern is used to create families of objects.


 Builder pattern is used to create complex object in steps with different
representations.
 Factory Method pattern uses subclass to create object of a derived
class of another class which is not known.
 Prototype pattern is used to create an object by cloning a prototype.
 Singleton pattern is used to create one and only one instance of a
class.

Abstract Factory Design Pattern


Abstract Factory design pattern is used to create families of objects.

Intent
 Provide an interface for creating families of related or dependent
objects without specifying their concrete classes.

The intent is to provide an interface through which families of related or


dependent objects can be created. Also while creation, the concrete classes
of those objects should not be specified.

Problem
 Instantiation of families of related objects.

Instantiation of objects in application will require hard coding of classes which


will make it difficult to manage and modify later. Also the objects are related to
a family and will be used together, so the change of family will be
cumbersome. There is another problem, when we try to add new family and
new product, we may end up creating objects based on multiple scenarios
using if, switch as the number of families and their objects grow.
Solution
 Come up with a way to create the family of objects.
 Separate the instantiation of objects from use.

Where it is applicable?
 We have to create set of objects which are going to work together.
 Supporting different families like system, OS or different versions of
product.
 Creation of products has to be separated from use.
 Interface has to be provided to outside world; and there is a need to
hide implementation like in case of libraries, frameworks, plug-ins.

Structure

Participant classes
 AbstractFactory provides interface for creating product objects.
 ConcreteFactory classes derived from the AbstractFactory
implements the methods for creating product objects. Each concrete
class represents one family, so we can say ConcreteFactory1 has the
methods to create objects for Series 1 product objects and
ConcreteFactory2 has the methods to create objects for Series 2
product objects.
 AbstractProduct classes provides interface for operations on
Products.
 Product classes are concrete classes derived from AbstractProduct
classes to implement the methods for Product.
 Client uses the Factory and Product.

How they work together?


 ConcreteFactory creates the family of products. ConcreteFactory1
class methods are creating series 1 products and ConcreteFactory2
class methods are creating series 2 products.
 So you can see client does not have any information of concrete
product classes for creating objects as it is in method of
ConcreteFactory class. Also each concrete factory is creating set of
objects for a family and Client is using these objects, so here the
instantiation is separated from use.
 So if tomorrow we have to replace the family then it will be easy as the
concrete factory is used only at one place in application and we will get
another set of product for a family by changing the concrete factory.
 How about adding of a new product. This looks complicated as
AbstractFactory and ConcreteFactory will require adding method for
each product, so can we think of adding methods dynamically, may be
but that will require separate discussion.
 If you see here each family requires one ConcreteFactory, so
ConcreteFactory can be implemented as Singleton.

Example
We want to create set of objects to manage the system. The families are
Unisys and IBM.

SystemManagementFactory is the abstract class which provides interface for


creating set of objects for a family. UnisysSMFactory is the concrete class
which implements methods for creating objects of Unisys family.
IBMSMFactory is the concrete class which implements methods for creating
objects of IBM family. Application uses the ConfigurationManager and
OperationManager for a particular family.

Factory Method Design Pattern


Factory Method design pattern uses subclass to create object of a derived
class of another class which is not known.

Intent
 Define an interface for creating an object, but let subclasses decide
which class to instantiate. Factory Method lets a class defer
instantiation to subclasses.

So the intent is to create the object through subclass.

Problem
 A class has to instantiate subclass of another class but does not know
which one.

We may have the scenario of Framework where a class has to create an


object of derived class of another class, but it does not have information of
that derived class. In other words we can say, user of the framework wants to
have his own derived class and another class of framework has to create the
object of derived class created by user. So it's obvious that derived class
information will not be available as it is created by user of framework only.

Solution
 Redefine a method in derived class which will decide which subclass to
instantiate.

We can have an abstract method as factory method which is redefined in


derived classes and in this method only required object is instantiated.

Where it is applicable?
 Framework and Libraries
 A class does not know the object it has to instantiate or it wants the
objects to be created by its subclass.
 Parallel class hierarchies

Structure
Participant classes
 Product class provides the interface for object to be created by
method FactoryMethod().
 ConcreteProduct is derived from Product and implements the
interface.
 Creator class has abstract method FactoryMethod(). It also has
method AnOperation() which uses FactoryMethod().
 ConcreteCreator is derived from Creator and implements the
FactoryMethod().

How they work together?


 Creator wants to create the object of ConcreteProduct but it does not
have the information of this class. So method AnOperation() of class
Creator calls the FactoryMethod() which is abstract method and
implemented in subclass ConcreteCreator, so this instantiates the
object of ConcreteProduct and returns the instantiated object to
Creator.
 Sometimes it is required to pass some input and create objects based
on that input.
 It provides lot of flexibility for plug-ins, parallel hierarchies and used
heavily in different design.

Example
We have framework of IDE and we want to add the support for Unisys project
and IBM project.
 UnisysProject and IBMProject classes are derived from abstract class
Project.
 Suppose the ProjectCreator class wants to create new project which is
object of UnisysProject. It has abstract method CreateProject() which is
implemented in derived class UnisysProjectCreator. It calls
CreateProject() method in NewProject(), so CreateProject() method of
class UnisysProjectCreator instantiates the object of class
UnisysProject and returns it to NewProject().
 So we can see the subclass has instantiated the object which was
known later only.

Builder Design Pattern


Builder design pattern is used to create complex object in steps with different
representations.

Intent
 Separate the construction of a complex object from its representation
so that the same construction process can create different
representations.

The intent is to separate the construction process of complex object and its
different representation uses the same construction process.

Problem
 Construction of complex object which requires different
representations.
Sometime complex object requires to be created in steps and then comes the
final object, so it's like creating component and assembling it into final
product. Also sometime it is required to have different representation, so
different components are required for assembling of a particular product.

So having the construction and representation together will make it complex


and will be difficult to modify and extend in future.

Solution
 Come up with way to create complex object in steps.
 Construction process should be separated from representation of
object.
 Provide the way for different representation of object.

Where it is applicable?
 A complex object has to be created in steps.
 Same construction process of object is required to provide different
representation of final object.
 The construction process requires separation from representation.

Structure

Participant classes
 Builder provides interface for creating parts of object.
 ConcreteBuilder class is derived from Builder and implements the
methods of Builder for creating parts of object. This assembles the part
to make a final product. It has the representation of objects and
provides the interface to get the created object.
 Director class has Builder as aggregation, it uses builder interface for
constructing the object.
 Product represents object to be created.
How they work together?
 Client uses the Director and provides the information for the product it
wants to create. Director has construction logic based on the provided
information, and uses builder interface to create parts of object,
concrete builder methods create the part of the object and assemble
them for a required product. The builder provides the product to
Director through its interface.
 So you can see construction process is separated from representation
of object. The internal structure of object is not known to the outside
world as it is with concrete builder only.
 The construction process has a way to create object in parts and well
managed by Director.
 New representation of object will require adding new concrete builder
which can be easily added. Also it will be easy to modify the
construction logic and representation of objects.
 Some scenarios may require access of intermediate object and has to
be taken care through builder. You can see, there is no interface for
product as final objects will be quite different and also well known to
client as it provides the input.
 Builder has all the methods for creating parts of objects, so the
required ones have to be implemented in concrete builder.

Prototype Design Pattern


Prototype design pattern is used to create an object by cloning a prototype.

Intent
 Specify the kinds of objects to create using a prototypical instance, and
create new objects by copying this prototype.

So the intent is to create an object by using prototype.

Problem
 Framework needs to instantiate application specific objects.

That means we have a class in framework which wants to create application


specific objects but does not know how to create and get those objects.

Solution
 Application can use the cloning of instance for subclasses.
We can have a prototype instance which is used to get abstract behavior of
Prototype and clone the objects of subclasses.

Where it is applicable?
 Framework to be used by developer
 To avoid parallel hierarchies.
 Wherever it is good to have a prototype and clone it, instead of creating
a new object every time.

Structure

Participant classes
 Prototype class has abstract method Clone(). It provides interface for
cloning the object.
 ConcretePrototype classes are derived from Prototype and
implements the Clone() method. These classes clone their respective
object and returns it to client.
 Client has the prototype instance and uses its interface for cloning.

How they work together?


 Client has instance of Prototype. It uses the Clone() method of
Prototype to clone itself.
 It is hiding internal information of product. We can have products added
or removed at run time by having prototype instance whenever
required. Reduces subclasses by avoiding parallel hierarchies. You
can have prototype instance as part of another object.
 It requires Clone() method in every prototype class. It may be difficult to
add in existing classes. Also sometime it will be difficult when object
does not support copy and has circular reference.
 We can have Prototype Manager which will manage all the prototypes
that includes registering and removing. Client can just use Prototype
Manager with well-defined access.
 Cloning has to be taken care appropriately like in case of circular
reference. We should be able to make difference for the use of shallow
or deep copy for different scenario. Also there may be requirement for
having state of objects which may require separate method for
initialization.
 Prototype is very useful pattern and generally used with other patterns
too.

Singleton Design Pattern


Singleton design pattern is used to create one and only one instance of a
class.

Intent
 Ensure a class only has one instance, and provide a global point of
access to it.

The intent is to have only one instance of a class and it should be accessible
to multiple clients through well-defined access point.

Problem
 Application requires only one instance of the class and that instance of
class should be accessible to multiple clients.

There are scenarios where one and only one instance of class is required, for
example File System, System Manager etc and it has to be accessed from
multiple applications. Introducing of global variable provides access to
multiple applications but does not make sure that there will be only one
instance.

Solution
 Make sure only one instance of class is created and the same one is
accessible to multiple clients.

The class itself can take the responsibility of creation of not more than one
instance and can provide the well-defined access point for multiple
applications.
Where it is applicable?
 One and only one instance of a class is required and well-defined
access point is provided to access it by multiple applications.

Structure

Participant classes
 Singleton class has method Instance() which has responsibility to
create single instance and is access point for providing the instance to
multiple applications. The class has data member uniqueInstance
which keeps the instance information.

How they work together?


 Client uses Instance() method of Singleton class to get the instance of
this class. The Instance() method checks for the instance, if instance is
already created then it returns the same, otherwise it creates the
instance and returns it to the client.
 The access of instance of class is controlled and well-defined. It also
provides scope to have variable number of instance with small
modification, if required in some scenario. The constructor has to be
protected so that it cannot be instantiated directly by client. Here
Instance uses lazy initialization as instance is created when it is first
used. The subclassing can be supported in multiple ways, one way
may be to register the instances and provide them when it is required
by returning the appropriate one.

Structural Design Patterns


Structural design patterns are concerned with the composition of classes or
objects to form larger structures. These are the patterns comes under
structural design patterns.

 Adapter pattern is used to provide a way for reusing an existing class.


 Bridge pattern is used to have interface and implementation
independently in separate hierarchies.
 Composite pattern is used to handle primitive and composite objects
uniformly.
 Decorator pattern is used to add additional responsibilities to an object
dynamically.
 Facade pattern is used to provide simple interface to use an existing
system in an easy way.
 Flyweight pattern is used to support sharing of objects when the
objects are in large number with details to granularity of system.
 Proxy pattern is used to provide a place holder for an object to control
its access.

Adapter Design Pattern


Adapter design pattern is used to provide a way for reusing an existing class.

Intent
 Convert the interface of a class into another interface clients expect.
Adapter lets classes work together that could not otherwise because of
incompatible interfaces.

The intent is to convert the interface of existing class to the one which client is
expecting.

Problem
 Want to use existing system/component but the current system used
by client does not have interfaces that are compatible with existing one.

The client has the interface that he wants to use, we have an existing class
which can be reused but it has different interface. So either a new class is
required or we have to find a way to use the existing one.

Solution
 Come up with a class which adapts the interface of existing
system/component to the new one which client expects.

The system will adapt the existing interface and will provide it in the way client
expects.

Where it is applicable?
 There is an existing class which we want to use in a system and may
require to provide interface in the way applicable for the system. Or we
can say we want to reuse the class but we don't have compatible
interfaces.

Structure
Composition

Composition structure also called as object adapter.

Participant Classes
 Target class provides interfaces to clients and has abstract method
Request().
 Adapter class is derived from Target class and implements the method
Request().
 Adaptee has the functionality we want to reuse.

How they work together?


 The Adapter class has instance of Adaptee and it adapts the methods
of Adaptee class. The method Request() of Adapter class in turn uses
the method SpecificRequest() of Adaptee. The client is required to use
the abstract method Request() only.
 Suppose we want to use another method which is not available in
Adaptee then we can just provide that method in Adapter class itself.
 We can also have multiple adaptees and adapter can have their
instance and adapts the functionality it requires.

Structure
Inheritance

Inheritance structure is also called as class adapter.

Participant Classes
 Target class provides interfaces to clients and has abstract method
Request().
 Adapter class is derived from Target and Adaptee. It implements the
method Request() and inherits the functionality of Adaptee.
 Adaptee has the functionality we want to reuse.

How they work together?


 Adapter class is derived from Adaptee, so that it can adapt the Adaptee
methods. The method SpecificRequest() is called in method Request()
of class Adapter which is provided as interface to client.

Example
We want to reuse already available class for HP System operations.
OperationManager class provides the interface ShutDown() to client.
Concrete class HPOperationManager implements the method ShutDown().
The class HPOPSystem already exists and provides the functionality through
its method PowerOff(). HPOperationManager has instance of HPOPSystem
and uses it in ShutDown() method to call the method PowerOff().

Bridge Design Pattern


Bridge design pattern is used to have interface and implementation
independently in separate hierarchies.

Intent
 Decouple an abstraction from its implementation so that the two can
vary independently.

The intent is to make abstraction and implementation independent.

Problem
 Implementation classes derived from abstract class makes difficult to
modify, extend and adding of new implementation classes.

When we use inheritance for abstraction class and implementation class then
the abstraction binds with implementation. This makes it complex to further
modify and extend. Also as more implementation classes are required with
variation, then it becomes complex to add more and more in same hierarchy
as the variation may come in different forms – like OS, system etc.

Solution
 Come up with interfaces for implementation.
 Derive the implementation classes from abstract implementation class.
 Use the interfaces of implementation in concrete class of abstract
class.

So the abstraction and implementation will be independent and will have their
own hierarchy.

Where it is applicable?
 Binding between abstraction and implementation has to be avoided.
 To reduce further subclassing by making abstraction and
implementation in separate hierarchy.

Structure

Participant classes
 Abstraction class provides the interface to the client and has the
instance of Implementor class.
 RefinedAbstraction class is derived from Abstraction class and
implements the interfaces.
 Implementor class has the interfaces implemented by implementation
classes.
 ConcreteImplementorA and ConcreteImplementorB classes
implements the methods of Implementor class.

How they work together?


 Client uses the interfaces from Abstraction class, the concrete class of
Abstraction class uses the instance of Implementor and uses its
interface which is implemented by concrete class of Implemetor, and
here it is ConcreteImplementorA and ConcreteImplementorB.
 The interface and implementation are separated and both are having
their own hierarchy. This makes it flexible to extend and maintain. It
also avoids subclassing explosion problem.
Example
To manage the system operations, we have to manage systems operations
and applications operations.

 Abstract class OperationManager provides interface Start() to client.


The concrete classes SystemOperation and ApplicationOperation
implements the method Start().
 Abstract class OperationManagerImp provides the interface Start() for
implementation. The concrete classes SystemOperationImp and
ApplicationOperationImp implements the method Start().
 The abstract class OperationManager has instance of
OperationManagerImp. The concrete class SystemOperation and
ApplicationOperation uses this instance to call the Start() method of
SystemOperationImp and ApplicationOperationImp.

Composite Design Pattern


Composite design pattern is used to handle primitive and composite objects
uniformly.

Intent
 Compose objects into tree structures to represent part-whole
hierarchies. Composite lets clients treat individual objects and
compositions of objects uniformly.

The intent is to compose the object to present part-whole hierarchy and


handle both primitive and composite object uniformly.

Problem
 The primitive and composite objects have to be handled differently. To
distinguish these objects for manipulation increases the complexity.

Solution
 Come up with a way to manipulate the primitive and composite object
uniformly.

That means both the primitive and composite object have to be handled in
similar manner.

Where it is applicable?
 When part-whole hierarchy of object has to be represented.
 Wherever primitive and composite objects have to be handled in similar
manner.
 Directories and Files in File system are the best example.

Structure
This is the UML structure of Composite design pattern-

Participant classes
 Component class provides the interface Operation().
 Concrete classes Leaf and Composite implements the method
Operation().

How they work together?


 Composite has instance of the class Component. It has objects which
can be Leaf and Composite as well. It traverses them and does the
operation on all the elements it has composed, either primitive or
composite.
 The method Add(), Remove() and GetChild() can be provided in
Component or Composite, its transparency vs safety. Providing it in
Component class makes it transparent and providing it in Composite
class makes it safe.
 So you can see both the primitive and composite objects are handled
in similar manner.

Decorator Design Pattern


Decorator design pattern is used to add additional responsibilities to an object
dynamically.

Intent
 Attach additional responsibilities to an object dynamically. Decorators
provide a flexible alternative to subclassing for extending functionality.

The intent is to provide flexible alternative to subclassing by adding


responsibilities to an object dynamically.

Problem
 Need to add additional functionality to object. Subclassing makes it
inflexible and complex.

We may require to add some additional functionality to the object. This may
be done by using inheritance but that will make it static and inflexible and
client will not be able to add functionality as it is required.

Solution
 Give the responsibility of adding additional functionality to another
object without using subclassing.

So additional functionality request will be forwarded to this object which will be


responsible for adding the required functionality.

Where it is applicable?
 Adding additional responsibility to an object dynamically.
 To avoid subclassing for extending functionality.

Structure

Participant classes
 Component class provides the interface to client for adding
functionality dynamically.
 ConcreteComponent class represents the object where additional
functionality will be added.
 Decorator class is derived from Component and has the responsibility
for adding additional functionality. It has instance of class Component.
 The concrete
classes ConcreteDecoratorA and ConcreteDecoratorB are used for
adding functionality to the Component object.

How they work together?


 Decorator does the Operation on ConcreteComponent as it has
instance of class Component. Extra functionality will be added by
method Operation() of ConcreteDecoratorA and ConcreteDecoratorB.
 This looks better than the subclassing, functionalities are added
dynamically and provide more flexibility. But this increases the number
of objects as the functionality increases and will make it difficult to
manage. So inheritance may work better if we have very less number
of functionality or functionality need not require to be added
dynamically.
Facade Design Pattern
Facade design pattern is used to provide simple interface to use an existing
system in an easy way.

Intent
 Provide a unified interface to a set of interfaces in a subsystem.
Facade defines a higher-level interface that makes the subsystem
easier to use.

The intent is to provide unified interface for a set of interfaces of subsystem to


make it easy to use.

Problem
 It is difficult for client to use the subsystem with existing interfaces.

The client has to use multiple interfaces of different subsystem classes to use
the existing subsystem. This makes using the subsystem complex as the
number of interfaces grow.

Solution
 Come up with a new simplified interface for client to use the system
easily.
The new simplified interface will use the existing subsystem interfaces. It will
be easy for client to use the new interface instead of using the multiple
subsystem interfaces and going into detail of knowing the existing subsystem
working and how the whole things are related.

Where it is applicable?
 There are lot of subsystem classes and it is complex to use the
subsystem as there is lot of dependency within them. So simple
interface for client makes it easy to use.

Structure

Participant classes
 Classes SybsystemClass1, SubsystemClass2 and SubsystemClas
s3 represent the existing complex subsystem which provides
functionality by using multiple interfaces.
 FacadeSystem class provides new simple interface to client.

How they work together?


 FacadeSystem has instances of classes SubsystemClass1,
SubsystemClass2 and SubsystemClass3. It uses their methods to
provide the functionality. Client uses the new provided interface
Method1 and Method2 of FacadeSystem. The client need not know the
details of existing complex system as it is taken care of by
FacadeSystem.
 the client just uses the interfaces provided by FacadeSystem and
FacadeSystem uses the appropriate subsystem interfaces in a way
required for a functionality. If required, subsystem can be used
independently too.

Proxy Design Pattern


Proxy design pattern is used to provide a placeholder for an object to control
its access.

Intent
 Provide a surrogate or placeholder for another object to control access
to it.

The intent is to provide a placeholder for another object and control its
access.

Problem
 Need to defer the instantiation of object until it is required.

Sometimes object creation and initialization may be very costly affair and may
affect performance, so it is better to defer the instantiation until it is required.

Solution
 Come up with another Proxy class which acts for real class and
instantiates the object of real class when required.

So we can have another class called proxy which will be placeholder for real
class and will instantiate the object of Real class when it is actually required.
Where it is applicable?
 The cost of object instantiation is high.
 Another object is required to present an object in different address
space called as remote proxy.
 There is access control required for an object, called as protection
proxy.

Structure

Participant classes
 Subject class provides the interface Request().
 Proxy class works as place holder for RealSubject. It has instance of
class RealSubject, so it creates the object of RealSubject and uses the
method of RealSubject. It can instantiate when operation is required on
RealSubject; and can provide access control too on RealSubject
object. Proxy implements the interface which is provided by Subject.
 RealSubject has actual functionality implementation of the interface
provided by Subject. Proxy presents as place holder for RealSubject.

How they work together?


 Client uses the Subject interface and proxy works as place holder for
RealSubject to avoid the high cost of instantiation. When any operation
is invoked, then only proxy instantiates the object of RealSubject and
then proxy uses the methods of RealSubject inside its methods to get
the functionality done.
 So we can see proxy is able to defer the instantiation and provide a
way to apply access control on RealSubject.
Behavioral Design Patterns
Behavioral design patterns characterize the ways in which classes or objects
interact and distribute responsibility. These are the patterns comes under
Behavioral design patterns.

 Chain of responsibility pattern is used to provide a chain of objects to


handle the request.
 Command pattern is used to encapsulate the request as an object.
 Interpreter pattern is used to define a problem in simple language and
resolving it through interpreting its simple sentences.
 Iterator pattern is used to access and traverse an aggregate object
without exposing its internal structure.
 Mediator pattern is used for controlling the interaction between different
objects.
 Memento pattern is used to capture the state of an object without
violating encapsulation, so that if required then it can be returned to its
previous state.
 Observer pattern is used to notify all the objects to update themselves
when an object state gets changed. This is also known as Publish-
Subscribe.
 State pattern is used to change the behavior of object based on current
state of object.
 Strategy pattern is used for selection of algorithm from a family of
algorithms based on context or data.
 Template Method pattern is used to get some steps of algorithm
implemented in subclass.
 Visitor pattern is used to perform operation on elements of an object
structure.

Interpreter Design Pattern


Interpreter design pattern is used to define a problem in simple language and
resolving it through interpreting its simple sentences.

Intent
 Given a language, define a representation for its grammar along with
an interpreter that uses the representation to interpret sentences in the
language.
The intent is to define the grammar for a language and use the interpreter to
interpret the simple sentences of the language using this grammar.

Problem
 A set of defined problem is coming again and again.

So the set of problem is well defined and coming repeatedly. As it is well


defined, it can be defined in language and simple sentences.

Solution
 Define the problem in sentences of language and interpret these
sentences to solve the problem.

So the set of well-defined problem can be defined in simple sentences of


language. We can come up with interpreter which can interpret these
sentences to solve the problem. So the solution comes in form of problem
defined in language and grammar, and interpreter is used to interpret it.

Where it is applicable?
 A set of well-defined problem can be represented in simple sentences
of language. That means the grammar of language has to be simple,
otherwise parser tools are better alternative.

Structure

Participant classes
 AbstractExpression class provides interface Interpret().
 TerminalExpression class represents the terminal symbol in grammar
and implements method Interpret().
 NonTerminalExpression class represents rule in the grammar and
will be there for every rule. This implements Interpret() method and
interprets every rule considering other rules.
 Context class has the context information and will be used while
interpretation of Terminal and Non Terminal expressions.
 Client has the representation of simple sentences of language with
defined grammar. This is in form of terminal and Non terminal
expressions.

How they work together?


 The client builds or gets the abstract syntax tree from the simple
sentences of language with defined grammar. Here sentence
represents the node of tree either terminal or non-terminal expression.
The rule of grammar represents the classes.
 Client has the context information and invokes the Interpret() method.
NonTerminalExpression interprets the expression based on rule of the
grammar. The TerminalExpression interprets the expression as
terminal. Interpreter knows the context information through context for
interpreting expression.
 So we can have interpreter to solve the problem defined in simple
sentences of language with defined grammar. Here it is easy to change
and add new grammar too. We can easily modify the interpreter also.
But it will be better to use parser tools if grammar is complex.
 There is an opportunity to use Flyweight pattern for terminal expression
if they are in large number as intrinsic and extrinsic state is easily
distinguishable.

Template Method Design Pattern


Template Method design pattern is used to get some steps of algorithm
implemented in subclass.

Intent
 Define the skeleton of an algorithm in an operation, deferring some
steps to subclasses. Template Method lets subclasses redefine certain
steps of an algorithm without changing the algorithm structure.

The intent is to defer some steps of algorithm to subclass without changing


the algorithm structure.

Problem
 The algorithm has to be generic but some steps are require to be
defined by user.

There may be a situation where steps of algorithm are not known. For
example, the framework has some steps of algorithm which are supposed to
be provided by user. There may be many scenarios where some steps may
vary but the algorithm is generic.

Solution
 Identify the invariant and variant part of the algorithm.
 Have the implementation of invariant part in abstract class and variant
part in derived class.

So the algorithm structure is not changed and some steps are deferred to be
implemented by subclasses.

Where it is applicable?
 The algorithm is generic with invariant and variant parts.
 The variant parts are required to be deferred to derived class.
 There is a need to provide extension points.

Structure

Participant classes
 AbstractClass has method TemplateMethod() which defines a generic
algorithm. It also has abstract methods PrimitiveOperation1() and
PrimitiveOperation2(). These methods are variant parts of generic
algorithm().
 ConcreteClass implements the abstract methods
PrimitiveOperation1() and PrimitiveOperation2().

How they work together?


 Client uses the TemplateMethod(). The generic algorithm defined in
TemplateMethod() calls the method of Concrete class to perform the
deferred steps.
 The invariant part of algorithm is executed in template method of
abstract class and variant part of algorithm is executed in concrete
class. This pattern is very useful for code reuse and generally used in
class libraries and frameworks.

Chain of Responsibility Design


Pattern
Chain of responsibility design pattern is used to provide a chain of objects to
handle the request.

Intent
 Avoid coupling the sender of a request to its receiver by giving more
than one object a chance to handle the request. Chain the receiving
objects and pass the request along the chain until an object handles it.

The intent is to chain the receiving objects to handle the request one by one
till it gets handled.

Problem
 Sender object does not know which object is going to handle the
request.

There may be a situation where the sender does not know which specific
object has to handle its request.

Solution
 Have multiple objects to handle the request of sender object.

So we can have multiple objects in chain and handle the request one by one
till the request is handled.
Where it is applicable?
 There may be multiple object which can handle the request.
 The sender object does not know which object can handle its request.

Structure

Participant classes
 Handler class provides interface HandleRequest() to client. It also has
member to keep the successor of handler object and method
MakeSuccessor() to set the successor.
 The concrete
classes ConcreteHandler1 and ConcreteHandler2 implement the
method HandleRequest().

How they work together?


 Client requests to handle the request, ConcreteHandler handles the
request if it can, otherwise it passes it to another object in chain
through successor information. So all the objects in chain one by one
try to handle the request in same way till last object.
 So we can see it decouples sender and requester. Also it provides
flexibility to add further responsibility in handler. There may be cases
when the request cannot be handled at all.

Command Design Pattern


Command design pattern is used to encapsulate the request as an object.

Intent
 Encapsulate a request as an object, thereby letting you parameterize
clients with different requests, queue or log requests, and support
undoable operations.

The intent is to encapsulate the request as an object, parameterize clients


with different requests, provide a queue, logging of requests and supporting
the undo operation.

Problem
 It is required to issue the requests to objects. The requested operation
and the receiver is not known.

There are scenarios where the requested operation and receiver is not known
and only receiver knows what operation has to be done.

Solution
 Come up with an object for requested operation, so that it can be
passed as any other object.

So the request can be encapsulated as an object, will be invoked and the


object will have receiver information which will carry out the operation.

Where it is applicable?
 The actions have to be performed but receiver and operation are not
known.
 Undo operation is required to be supported.
 Logging of actions are required to recover the system from crash using
logs.
 There are different types of actions that have to be invoked in a similar
manner.

Structure
Participant classes
 Command class provides interface Execute() to invoker.
 ConcreteCommand class implements the method Execute() which
uses the receiver to carry out the operation. It has instance of class
Receiver.
 Invoker class has the instance of class Command and invokes the
command interface to carry out the operation.
 Receiver class has methods to do the operation for a request.

How they work together?


 Client creates the object of class ConcreteCommand and sets its
receiver. Invoker has the instance of this object and it invokes the
request using the interface Execute(). The Execute() method of
ConcreteObject uses the receiver to do the operation.
 The command pattern is decoupling the invoker and receiver. This
provides flexibility to add new commands and modify the existing ones.
 There can be easy facility of Undo operation with added operation
Unexecute or Undo in Command object. This may require storing of
states and having the history list for execution of commands, so redo
operation can be provided as well.
 There can be MacroCommand which manages the sequence of
commands. This will have list of commands and will execute them one
by one with simple traversal.

Iterator Design Pattern


Iterator design pattern is used to access and traverse an aggregate object
without exposing its internal structure.

Intent
 Provide a way to access the elements of an aggregate object
sequentially without exposing its underlying representation.

The intent is to provide the access of aggregate object without exposing its
internal structure.

Problem
 Need to access the elements of an aggregate object without exposing
the internal details of object.
Accessing elements of object is required with traversal, and at the same time
it should not expose the internal structure of aggregate object. Also this may
be applicable to different data structures, which provide different algorithms
for accessing and traversing.

Solution
 Provide a way to access and traverse an aggregate object by giving
responsibility of access and traversal to another object.

So there can be common interface, which can be applicable for different data
structures to provide interface for accessing and traversing. There will be
separate objects having this interface and will have responsibility to access
the elements and traversal of aggregate objects.

Where it is applicable?
 Access and traversal of aggregate object is required without exposing
its internal structure.
 Common interface is required to access and traverse different data
structures.

Structure
Participant classes
 Iterator class provides the interface for accessing the elements and
traversal of the aggregate object.
 ConcreteIterator class implements the interface of Iterator class and
keeps track of current item of aggregate object.
 Aggregate class provides the interface for creating Iterator object.
 ConcreteAggregate class implements the method CreateIterator().

How they work together?


 The client creates the ConcreteAggregate object. It uses the
CreateIterator interface to create the ConcreteIterator object. This will
have the current item information to track the aggregate object. Now it
uses the Iterator interface to access the elements and traversal of
aggregate object.
 So we can have different data structures, and their concrete iterators
can implement interface according to their traversal algorithm. This
makes the access and traversal simple for different data structures.

Mediator Design Pattern


Mediator design pattern is used for controlling the interaction between
different objects.

Intent
 Define an object that encapsulates how a set of objects interact.
Mediator promotes loose coupling by keeping objects from referring to
each other explicitly, and it lets you vary their interaction independently.

The intent is to have an object to encapsulate the interaction of different


objects.

Problem
 There is too much communication between objects, which is increasing
the complexity and making it difficult to reuse the objects.

Too much communication between objects increases dependency between


them, makes the system complex and reduces the reusability of objects. Also
extending the behavior requires more subclasses.

Solution
 Encapsulate the behavior of interaction and coordination in a separate
object.

There can be a separate object, which will encapsulate the behavior of


interaction of the communicating objects. It will also have responsibility for
coordinating the interaction of objects. So objects will communicate through
this object only.

Where it is applicable?
 There are set of objects with lot of interaction within them, thus
increasing the dependency.
 It's becoming difficult to reuse the objects, because of too much
interaction and dependency.
 Behavior has to be customizable without subclassing.

Structure

Participant classes
 Mediator class provides interface for interaction between colleague
objects.
 ConcreteMediator class implements the method and does the
coordination between colleague objects as required for behavior. This
has the instance of applicable colleague objects.
 Colleague class provides interface for Colleague objects. It also has
the instance of Mediator object.
 ConcreteColleague class implements the method and keeps the
instance of respective concrete mediator object.

How they work together?


 Colleague object requests mediator object for interaction with any other
colleague object. Mediator object handles the request and coordinates
the communication between colleague objects as required for a
particular behavior.
 So the mediator object is encapsulating the interaction, so that objects
can be reused. It also reduces subclassing, as behavior can be added
or modified in mediator easily. The protocol for communication can be
defined in Mediator and can be easily modified as Mediator behaves
like central controlling object for interaction.

Memento Design Pattern


Memento design pattern is used to capture the state of an object without
violating encapsulation, so that if required then it can be returned to its
previous state.

Intent
 Without violating encapsulation, capture and externalize an object’s
internal state so that the object can be restored to this state later.

The intent is to capture the internal state of object without violating


encapsulation, and restore to the same state if required.

Problem
 Need to save state of an object to restore it later. Saving it externally is
difficult as it violates encapsulation.

There may be scenarios like undo, rollback, handling exceptions where object
has to be restored to previous state.

Solution
 Store the state of the object in another object and make it accessible
from the object whose state is saved.

The object state will be saved in another object which will be created and
accessed by same object so it will not violate the encapsulation.

Where it is applicable?
 An Exception has to be handled in a way where an object has to be
restored to its previous state.
 The object state has to be stored somewhere to restore it later but
should not be accessed by anyone, other than the object whose state
is saved.
 The scenarios of undo and rollback operations.

Structure

Participant classes
 Originator class has the state to be captured. The method
CreateMemnto() is used to instantiate the Memento object which stores
the state of the originator object; and Method SetMemnto() is used to
get the previous state and restore the same.
 Memento class keeps the internal state of the originator object and can
be accessed by originator only.
 Caretaker class keeps the Memento object safely, this is nothing but a
mechanism for undo or rollback.

How they work together?


 The client uses caretaker which requests originator to have a
memento; and if undo or rollback is required then pass the memento to
originator for restoring the object state. Originator accesses its previous
state from memento and restores the same.
 So the object state is stored externally; and if required then it can be
accessed to restore the same without violating encapsulation. This may
be expensive if object is large or many mementos have to be created.
There may be possibility to store state with incremental changes too.

What is CodeIgniter? How does CI


Framework Work?
What is CodeIgniter?
CodeIgniter is a PHP MVC framework used for developing web
applications rapidly. CodeIgniter provides out of the box libraries for
connecting to the database and performing various operations like
sending emails, uploading files, managing sessions, etc.

CodeIgniter Features
Let's see some of the features that make CodeIgniter great. The
following list is not exhaustive but gives you an idea of what to expect
when working with CodeIgniter.

Small footprint

The entire source code for CodeIgniter framework is close to 2MB.


This makes it easy to master CodeIgniter and how it works. It also
simplifies deploying and updating it.

Blazing fast

Users tend to favor applications that load very fast. If you have
worked with some of the modern frameworks, then you will realize
that they take less than one second to load just after installation.
CodeIgniter, you can loads on average around less than 50ms. The
extra time spent optimizing like is the case in another framework is
freed up when you are working with CodeIgniter framework.
21.8M
285
What is Linux Linux Beginner Tutorial

Loosely coupled

The built-in features are designed to work independently without relying too
much on other components. This makes it easy to maintain and make
upgrades

MVC Architecture

The PHP CodeIgniter framework uses the Model-View-Controller


architectural design. It is industry standard practices when working with
web applications. MVC separates the data, business logic, and presentation.

Excellent documentation:
The framework is well documented, and there are good books, tutorials and
answered forum questions on CodeIgniter. This means whatever challenge
that you have, chances are someone has already encountered the problem,
solved it and the solution is out there for you.

Application specific built-in components:

CodeIgniter has components for sending email, database management,


session management and many more as you will discover as we continue
with the tutorials.

Extendable:

CodeIgniter comes with some libraries, and helpers out of the box. If what
you want is not there or you would like to implement an existing feature
your way. Then you can do so easily by creating your libraries, helpers,
packages, etc. You can also create REST API in CodeIgniter.

Short learning curve:

CodeIgniter is easy to master for anyone who is already familiar with PHP.
Within a very short time, the student can Learn CodeIgniter and start
developing professional applications using CodeIgniter.

How CodeIgniter Works?


CodeIgniter is an MVC framework. MVC stands for Model View
Controller. When a user requests a resource, the controller responds first.
The controller understands the user request then request the necessary data if
necessary.

For example, if you want to retrieve a customer with the id= 3, the controller
will receive your request, then request the CodeIgniter models to retrieve the
record with the id of 3. The CodeIgniter models will return the record to the
controller. The controller then forwards the result to the view which formats
it into a human-readable format. Then the results are returned to the user in
the browser.

The following image shows how CodeIgniter works:


CodeIgniter Release History
2006 First version of CodeIgniter

2009 ExpressionEngine 2.0 launched

2014 British Columbia Institute of Technol


took ownership of the project

2020 On February 24, CodeIgniter 4 was off


launched

Summary
 CodeIgniter is a PHP framework for developing applications rapidly
 The entire source code for CodeIgniter is close to 2MB. This makes it
easy to master CodeIgniter and how it works
 The built-in features of CodeIgniter are designed to work
independently without relying too much on other components
 The framework uses the Model-View-Controller architectural design
 The framework is well documented, and they are good books,
tutorials and answered forum questions on CodeIgniter
 CodeIgniter comes with some libraries, and helpers users out of the
box
 CodeIgniter is easy to master for anyone who is already familiar with
PHP
 In CodeIgniter user requests a resource, the controller responds first.
The controller understands the user request then request the necessary
data if it is important
 Codeigniter 4 was released On February 24, 2020, the birthday of Jim
Parry, who was the project lead of Codeigniter 4 and died on January
15, 2020

Django introduction
 Overview: Django
 Next
In this first Django article, we answer the question "What is Django?" and give
you an overview of what makes this web framework special. We'll outline the
main features, including some of the advanced functionality that we won't have
time to cover in detail in this module. We'll also show you some of the main
building blocks of a Django application (although at this point you won't yet
have a development environment in which to test it).

Basic computer literacy. A general understanding of server-side w


Prerequisites:
particular the mechanics of client-server interactions in website

To gain familiarity with what Django is, what functionality it pro


Objective:
blocks of a Django application.

What is Django?
Django is a high-level Python web framework that enables rapid development
of secure and maintainable websites. Built by experienced developers, Django
takes care of much of the hassle of web development, so you can focus on
writing your app without needing to reinvent the wheel. It is free and open
source, has a thriving and active community, great documentation, and
many options for free and paid-for support. 

Django helps you write software that is:

Complete
Django follows the "Batteries included" philosophy and provides
almost everything developers might want to do "out of the box".
Because everything you need is part of the one "product", it
all works seamlessly together, follows consistent design
principles, and has extensive and up-to-date documentation.
Versatile
Django can be (and has been) used to build almost any type of
website — from content management systems and wikis, through
to social networks and news sites. It can work with any
client-side framework, and can deliver content in almost any
format (including HTML, RSS feeds, JSON, XML, etc). The site
you are currently reading is built with Django!

Internally, while it provides choices for almost any


functionality you might want (e.g. several popular databases,
templating engines, etc.), it can also be extended to use other
components if needed.

Secure
Django helps developers avoid many common security mistakes by
providing a framework that has been engineered to "do the right
things" to protect the website automatically. For example,
Django provides a secure way to manage user accounts and
passwords, avoiding common mistakes like putting session
information in cookies where it is vulnerable (instead cookies
just contain a key, and the actual data is stored in the
database) or directly storing passwords rather than a password
hash.

A password hash is a fixed-length value created by sending the


password through a cryptographic hash function. Django can
check if an entered password is correct by running it through
the hash function and comparing the output to the stored hash
value. However due to the "one-way" nature of the
function, even if a stored hash value is compromised it is
hard for an attacker to work out the original password.

Django enables protection against many vulnerabilities by


default, including SQL injection, cross-site scripting, cross-
site request forgery and clickjacking (see Website
security for more details of such attacks).

Scalable
Django uses a component-based “shared-nothing” architecture
(each part of the architecture is independent of the others,
and can hence be replaced or changed if needed). Having
a clear separation between the different parts means that it
can scale for increased traffic by adding hardware at
any level: caching servers, database servers, or application
servers. Some of the busiest sites have successfully scaled
Django to meet their demands (e.g. Instagram and Disqus, to
name just two).

Maintainable
Django code is written using design principles and patterns
that encourage the creation of maintainable and reusable code.
In particular, it makes use of the Don't Repeat Yourself (DRY)
principle so there is no unnecessary duplication, reducing the
amount of code. Django also promotes the grouping of related
functionality into reusable "applications" and, at a lower
level, groups related code into modules (along the lines of
the Model View Controller (MVC) pattern).

Portable
Django is written in Python, which runs on many platforms. That
means that you are not tied to any particular server platform,
and can run your applications on many flavours of Linux,
Windows, and Mac OS X. Furthermore, Django is well-supported
by many web hosting providers, who often provide specific
infrastructure and documentation for hosting Django sites.

Where did it come from?


Django was initially developed between 2003 and 2005 by a web team who
were responsible for creating and maintaining newspaper websites. After
creating a number of sites, the team began to factor out and reuse lots of
common code and design patterns. This common code evolved into a generic
web development framework, which was open-sourced as the "Django"
project in July 2005. 

Django has continued to grow and improve, from its first milestone


release (1.0) in September 2008 through to the recently-released version
3.1 (2020). Each release has added new functionality and bug fixes, ranging
from support for new types of databases, template engines, and caching,
through to the addition of "generic" view functions and classes (which reduce
the amount of code that developers have to write for a number of programming
tasks). 

Note

Check out the release notes on the Django website to see what has changed
in recent versions, and how much work is going into making Django better.

Django is now a thriving, collaborative open source project, with many


thousands of users and contributors. While it does still have some features that
reflect its origin, Django has evolved into a versatile framework that is capable
of developing any type of website.

How popular is Django?


There isn't any readily-available and definitive measurement of popularity of
server-side frameworks (although you can estimate popularity using
mechanisms like counting the number of GitHub projects and StackOverflow
questions for each platform). A better question is whether Django is "popular
enough" to avoid the problems of unpopular platforms. Is it continuing to
evolve? Can you get help if you need it? Is there an opportunity for you to get
paid work if you learn Django? 

Based on the number of high profile sites that use Django, the number of
people contributing to the codebase, and the number of people providing both
free and paid for support, then yes, Django is a popular framework!

High-profile sites that use Django include: Disqus, Instagram, Knight


Foundation, MacArthur Foundation, Mozilla, National Geographic, Open
Knowledge Foundation, Pinterest, and Open Stack (source: Django overview 
page).

Is Django opinionated?
Web frameworks often refer to themselves as "opinionated" or
"unopinionated".

Opinionated frameworks are those with opinions about the "right way" to
handle any particular task. They often support rapid development in a
particular domain (solving problems of a particular type) because the right way
to do anything is usually well-understood and well-documented. However they
can be less flexible at solving problems outside their main domain, and tend to
offer fewer choices for what components and approaches they can use.

Unopinionated frameworks, by contrast, have far fewer restrictions on the best


way to glue components together to achieve a goal, or even what components
should be used. They make it easier for developers to use the most suitable
tools to complete a particular task, albeit at the cost that you need to find those
components yourself.

Django is "somewhat opinionated", and hence delivers the "best of both


worlds". It provides a set of components to handle most web development
tasks and one (or two) preferred ways to use them. However, Django's
decoupled architecture means that you can usually pick and choose from a
number of different options, or add support for completely new ones if desired.

What does Django code look like?


In a traditional data-driven website, a web application waits for HTTP requests
from the web browser (or other client). When a request is received the
application works out what is needed based on the URL and possibly
information in POST data or GET data. Depending on what is required it may
then read or write information from a database or perform other tasks required
to satisfy the request. The application will then return a response to the web
browser, often dynamically creating an HTML page for the browser to display
by inserting the retrieved data into placeholders in an HTML template.

Django web applications typically group the code that handles each of these
steps into separate files:

 URLs: While it is possible to process requests from every single URL


via a single function, it is much more maintainable to write a separate
view function to handle each resource. A URL mapper is used to
redirect HTTP requests to the appropriate view based on the request
URL. The URL mapper can also match particular patterns of strings or
digits that appear in a URL and pass these to a view function as data.
 View: A view is a request handler function, which receives HTTP
requests and returns HTTP responses. Views access the data needed
to satisfy requests via models, and delegate the formatting of the
response to templates.
 Models: Models are Python objects that define the structure of
an application's data, and provide mechanisms to manage (add, modify,
delete) and query records in the database. 

 Templates: A template is a text file defining the structure or layout of a


file (such as an HTML page), with placeholders used to represent actual
content. A view can dynamically create an HTML page using an HTML
template, populating it with data from a model. A template can be used
to define the structure of any type of file; it doesn't have to be HTML!

Note

Django refers to this organization as the "Model View Template (MVT)"


architecture. It has many similarities to the more familiar Model View
Controller architecture. 

The sections below will give you an idea of what these main parts of a Django
app look like (we'll go into more detail later on in the course, once we've set up
a development environment).

Sending the request to the right view (urls.py)


A URL mapper is typically stored in a file named urls.py. In the example
below, the mapper (urlpatterns) defines a list of mappings
between routes (specific URL patterns) and corresponding view functions. If
an HTTP Request is received that has a URL matching a specified pattern,
then the associated view function will be called and passed the request.

urlpatterns = [

path('admin/', admin.site.urls),

path('book/<int:id>/', views.book_detail, name='book_detail'),

path('catalog/', include('catalog.urls')),

re_path(r'^([0-9]+)/$', views.best),]

Copy to Clipboard

The urlpatterns object is a list of path() and/or re_path() functions


(Python lists are defined using square brackets, where items are separated by
commas and may have an optional trailing comma. For example: [item1,
item2, item3,]).

The first argument to both methods is a route (pattern) that will be matched.
The path() method uses angle brackets to define parts of a URL that will be
captured and passed through to the view function as named arguments.
The re_path() function uses a flexible pattern matching approach known as a
regular expression. We'll talk about these in a later article!

The second argument is another function that will be called when the pattern is
matched. The notation views.book_detail indicates that the function is
called book_detail() and can be found in a module called views (i.e. inside
a file named views.py)

Handling the request (views.py)


Views are the heart of the web application, receiving HTTP requests from web
clients and returning HTTP responses. In between, they marshal the other
resources of the framework to access databases, render templates, etc. 

The example below shows a minimal view function index(), which could have
been called by our URL mapper in the previous section. Like all view functions
it receives an HttpRequest object as a parameter (request) and returns
an HttpResponse object. In this case we don't do anything with the request,
and our response returns a hard-coded string. We'll show you a request that
does something more interesting in a later section.

# filename: views.py (Django view functions)

from django.http import HttpResponse

def index(request):

# Get an HttpRequest - the request parameter

# perform operations using information from the request.

# Return HttpResponse

return HttpResponse('Hello from Django!')

Copy to Clipboard

Note

A little bit of Python:

 Python modules are "libraries" of functions, stored in separate files, that


we might want to use in our code. Here we import just
the HttpResponse object from the django.http module so that we can
use it in our view: from django.http import HttpResponse . There
are other ways of importing some or all objects from a module.
 Functions are declared using the def keyword as shown above, with
named parameters listed in brackets after the name of the function; the
whole line ends in a colon. Note how the next lines are all indented.
The indentation is important, as it specifies that the lines of code are
inside that particular block (mandatory indentation is a key feature of
Python, and is one reason that Python code is so easy to read).

Views are usually stored in a file called views.py.

Defining data models (models.py)


Django web applications manage and query data through Python objects
referred to as models. Models define the structure of stored data, including the
field types and possibly also their maximum size, default values, selection list
options, help text for documentation, label text for forms, etc. The definition of
the model is independent of the underlying database — you can choose one of
several as part of your project settings. Once you've chosen what database
you want to use, you don't need to talk to it directly at all — you just write your
model structure and other code, and Django handles all the "dirty work" of
communicating with the database for you.

The code snippet below shows a very simple Django model for a Team object.
The Team class is derived from the django class models.Model. It defines the
team name and team level as character fields and specifies a maximum
number of characters to be stored for each record. The team_level can be
one of several values, so we define it as a choice field and provide a mapping
between choices to be displayed and data to be stored, along with a default
value. 

# filename: models.py

from django.db import models

class Team(models.Model):

team_name = models.CharField(max_length=40)

TEAM_LEVELS = (

('U09', 'Under 09s'),

('U10', 'Under 10s'),


('U11', 'Under 11s'),

... #list other team levels

team_level = models.CharField(max_length=3, choices=TEAM_LEVELS,


default='U11')

Copy to Clipboard

Note

A little bit of Python:

 Python supports "object-oriented programming", a style of programming


where we organize our code into objects, which include related data
and functions for operating on that data. Objects can also
inherit/extend/derive from other objects, allowing common behavior
between related objects to be shared. In Python we use the
keyword class to define the "blueprint" for an object. We can create
multiple specific instances of the type of object based on the model in
the class.

So for example, here we have a Team class, which derives from


the Model class. This means it is a model, and will contain all the
methods of a model, but we can also give it specialized features of its
own too. In our model we define the fields our database will need to
store our data, giving them specific names. Django uses these
definitions, including the field names, to create the underlying database.
Querying data (views.py)
The Django model provides a simple query API for searching the associated
database. This can match against a number of fields at a time using different
criteria (e.g. exact, case-insensitive, greater than, etc.), and can support
complex statements (for example, you can specify a search on U11 teams that
have a team name that starts with "Fr" or ends with "al"). 

The code snippet shows a view function (resource handler) for displaying all of
our U09 teams. The line in bold shows how we can use the model query API
to filter for all records where the team_level field has exactly the text 'U09'
(note how this criteria is passed to the filter() function as an argument, with
the field name and match type separated by a double
underscore: team_level__exact).

## filename: views.py
from django.shortcuts import renderfrom .models import Team

def index(request):

list_teams = Team.objects.filter(team_level__exact="U09")

context = {'youngest_teams': list_teams}

return render(request, '/best/index.html', context)

Copy to Clipboard

This function uses the render() function to create the HttpResponse that is


sent back to the browser. This function is a shortcut; it creates an HTML file by
combining a specified HTML template and some data to insert in the template
(provided in the variable named "context"). In the next section we show how
the template has the data inserted in it to create the HTML.

Rendering data (HTML templates)


Template systems allow you to specify the structure of an output document,
using placeholders for data that will be filled in when a page is generated.
Templates are often used to create HTML, but can also create other types of
document. Django supports both its native templating system and another
popular Python library called Jinja2 out of the box (it can also be made to
support other systems if needed). 

The code snippet shows what the HTML template called by


the render() function in the previous section might look like. This template
has been written under the assumption that it will have access to a list variable
called youngest_teams when it is rendered (this is contained in
the context variable inside the render() function above). Inside the HTML
skeleton we have an expression that first checks if
the youngest_teams variable exists, and then iterates it in a for loop. On
each iteration the template displays each team's team_name value in
an <li> element.

## filename: best/templates/best/index.html

<!DOCTYPE html><html lang="en"><head>

<meta charset="utf-8">

<title>Home page</title></head><body>

{% if youngest_teams %}
<ul>

{% for team in youngest_teams %}

<li>{{ team.team_name }}</li>

{% endfor %}

</ul>

{% else %}

<p>No teams are available.</p>

{% endif %}</body></html>

You might also like