Blog by Leven

Useful Websites

In my future study in Denmark, I may need some very important and useful websites. In order to find them easily, I record them here.

Job hunting

glassdoor: https://www.glassdoor.com/index.htm
indeed: https://www.indeed.com
ida: https://ida.dk/

momondo: https://www.momondo.com/

Resume

europass: https://europass.cedefop.europa.eu/

Mobile phone card

Lebara: https://mobile.lebara.com/dk/da/

Music

My Free MP3: https://my-free-mp3s.com/cn

Denmark society

Living and working in Copenhagen https://international.kk.dk/indhold/living-and-working-copenhagen-non-eu-citizen

Danish

loecsen: https://www.loecsen.com/zh/%E8%AF%BE%E7%A8%8B-%E4%B8%B9%E9%BA%A6%E8%AF%AD

Facade-Pattern

What is Facade pattern

在软件工程中,隐藏系统的复杂性,并向客户端提供了可以访问系统的接口。这种类型的设计模式属于结构型模式
In the software engineering, Facade pattern can hide the complexities of the larger system and provide a simple interface to the client. This kind of design pattern is included in structural patterns.

The usage of Facade pattern

  1. advantage: easy for client; improve the safety

  2. disadvantage: not conform open-close principle; hard to modify.

Scene and example

门面模式的应用非常广泛。当需要屏蔽掉内部的细节,只给出简单接口的时候,你就会想到门面模式。它对客户非常友好。下面一个例子,是模拟计算机处理程序的过程。

Facade pattern is widely used in many applications. When you need to hide the internal details and give only simple interfaces, you will consider facade pattern. It is very friendly to client. The simple example shown below is simulating how computers deal with programs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

"""
Facade pattern example.
"""

# Complex computer parts
class CPU(object):
"""
Simple CPU representation.
"""
def freeze(self):
print("Freezing processor.")

def jump(self, position):
print("Jumping to:", position)

def execute(self):
print("Executing.")


class Memory(object):
"""
Simple memory representation.
"""
def load(self, position, data):
print("Loading from {0} data: '{1}'.".format(position, data))


class SolidStateDrive(object):
"""
Simple solid state drive representation.
"""
def read(self, lba, size):
return "Some data from sector {0} with size {1}".format(lba, size)


class ComputerFacade(object):
"""
Represents a facade for various computer parts.
"""
def __init__(self):
self.cpu = CPU()
self.memory = Memory()
self.ssd = SolidStateDrive()

def start(self):
self.cpu.freeze()
self.memory.load("0x00", self.ssd.read("100", "1024"))
self.cpu.jump("0x00")
self.cpu.execute()


computer_facade = ComputerFacade()
computer_facade.start()

Facade in Laravel

Laravel is a widely used php framework. In the framework, the facade pattern is a very important feature. This article (Understanding Laravel Facades) introduces how facade is used in Laravel. And if you want to create a new facade , you should follow for steps below,

  1. Create your own service YourService.php , it may look like this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    namespace App\Services\Api;

    class YourService {

    function __construct(){
    echo "function __constructed";
    }
    public function doSomething(){
    echo "function __doSomething";
    }
  2. Create a Facade class YourFacade.php,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    namespace App\Facades;

    use Illuminate\Support\Facades\Facade;

    class YourFacade extends Facade{
    protected static function getFacadeAccessor(){
    return 'your';
    }
    }
  3. Register your object into ServiceProvider YourServiceProvider.php,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    namespace App\Providers;

    use Illuminate\Support\ServiceProvider;
    use App\Services\Api\YourService;

    class YourServiceProvider extends ServiceProvider
    {
    /**
    * Bootstrap the application services.
    *
    * @return void
    */
    public function boot()
    {
    //
    }
    /**
    * Register the application services.
    *
    * @return void
    */
    public function register()
    {
    $this->app->singleton('your', function () {
    return new YourService();
    });
    }
    }
  4. Register your provider and alias name in config file \config\app.php(with this step you can use use AnyWord instead of referencing its location use App\Services\Api and this is the advantage of facade pattern ),

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    ... 
    'providers' => [
    ...
    App\Providers\YourServiceProvider::class
    ],
    ...

    'aliases' => [
    ...
    'AnyWord' => App\Facades\YourFacade::class
    ],
    ...

Reference document

wiki - Facade_pattern
Understanding Laravel Facades

Decorator-Pattern

What is decorator pattern

在软件工程中,装饰器模式允许向一个现有的对象添加新的功能,同时又不改变其结构。这种模式属于结构型模式,它是作为一个现有类的包装。
In software engineering, decorator pattern is a design pattern that alows new behaviour or function to be added to an existing individual object , without changeing the inheritance relationship or the behaviour of other objects from the same class. Decorator pattern is structural design pattern, and it is packaged of an existing object.

The usage of decorator pattern

意图:我们在设计阶段,会从子类或者抽象类,去考虑解决问题。但是在以后的扩展中,不想改变现有的类结构和让现有的子类过于膨胀,又希望给现有的对象添加一些新的功能,就会考虑使用装饰器模式。就增加功能来说,装饰器模式相比生成子类更为灵活。
如何解决:将具体功能职责划分,同时继承装饰类。
关键代码: 1、Component 类充当抽象角色,不应该具体实现。 2、修饰类引用和继承 Component 类,具体扩展类重写父类方法。
优点:装饰类可以动态扩展,不会给现有的类增加负担.
缺点:多层装饰比较复杂和难以理解。

Intent

In the process of designing, we ofen consider solving problems by defining subclasses or abstract classes. However, in the future expansion, wo do not want change the existing class structure and make the existing subclasses overstaffed, and want to add some new functions to the existing objects,we will consider using the decorator pattern.

How to solve

Divide the specific functions and resposibilities, meanwhile, inherit the decorator class.

Key code

  1. Component class act as absctract class and should not be implemented concretely.

  2. Decorate class refer and inherit Component class, extend the class concretely and rewrite methods in super class.

Advantage

Decorator class can be extended dynamically without adding burden to the existing class.

Disadvantage

Multi-layer decorators may be complex and hard to understand.

Scene and example

When we need to extend the functions of an existing object dynamically (dynamiccally increase and decrease), we use decorator pattern. For example, We have produced a new type of car and need to sell it. At this time, we can use several decorator classes, such as introducing its speed performance, safety performance and fuel-saving features so that customers can make up their minds to buy it.

class diagram

I implement this example by python3.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""
Decorator pattern example.
"""
from abc import ABC, abstractmethod

NOT_IMPLEMENTED = "You should implement this method."

# Role: Component
class CarSale():
@abstractmethod
def displayCarInfo(self):
raise NotImplementedError(NOT_IMPLEMENTED)


# Role: Concreted Class
class CarInfo(CarSale):

def displayCarInfo(self):
print("Price: 2000$")
print("Name: TOYOTA 2020")
print("Place of production: China")

#Role: Decorator Component
class SaleTalk(CarSale):
def __init__(self,car_sale):
self._car_sale = car_sale

#override
def displayCarInfo(self):
self._car_sale.displayCarInfo()


# Role Decorator1
class SpeedDecorator(SaleTalk):
def __init__(self,car_sale):
super().__init__(car_sale)

def __showSpeed(self):
print("Speed is fast, up to 500km/h")

def displayCarInfo(self):
super().displayCarInfo()
self.__showSpeed()

# Role Decorator2
class OilDecorator(SaleTalk):
def __init__(self,car_sale):
super().__init__(car_sale)

def __showOil(self):
print("More fuel-efficient than 90% of cars")

def displayCarInfo(self):
super().displayCarInfo()
self.__showOil()


# Role Client
car_info = CarInfo()
#car_info.displayCarInfo()
speed_decorator = SpeedDecorator(car_info)
#speed_decorator.displayCarInfo()
final_decorator = OilDecorator(speed_decorator)
final_decorator.displayCarInfo()

Reference document

wiki - Decorator_pattern

Composite-Pattern

what is composite pattern

In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes a group of objects that is treated the same way as a single instance of the same type of object. The intent of a composite is to “compose” objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

the usage of composite pattern

Composite should be used when clients ignore the difference between compositions of objects and individual objects. If programmers find that they are using multiple objects in the same way, and often have nearly identical code to handle each of them, then composite is a good choice; it is less complex in this situation to treat primitives and composites as homogeneous.

It can be used in partial/whole scene, such as tree menus, files/folder, tree-structured hierarchies.

the UML class object diagram for the Composite design pattern is shown below,

the UML class object diagram for the Composite design pattern

scene and example

Here is an example written in python, and it use child graphics to composite a multiple graphic through uniform Component(Graphic).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
Composite pattern example.
"""
from abc import ABC, abstractmethod

NOT_IMPLEMENTED = "You should implement this."


# Component
class Graphic(ABC):
@abstractmethod
def print(self):
raise NotImplementedError(NOT_IMPLEMENTED)

# "Composite"
class CompositeGraphic(Graphic):
def __init__(self):
self.graphics = []

def print(self):
for graphic in self.graphics:
graphic.print()

def add(self, graphic):
self.graphics.append(graphic)

def remove(self, graphic):
self.graphics.remove(graphic)

# "Leaf"
class Ellipse(Graphic):
def __init__(self, name):
self.name = name

def print(self):
print("Ellipse:", self.name)


# "Client"
ellipse1 = Ellipse("1")
ellipse2 = Ellipse("2")
ellipse3 = Ellipse("3")
ellipse4 = Ellipse("4")

graphic = CompositeGraphic()
graphic1 = CompositeGraphic()
graphic2 = CompositeGraphic()

graphic1.add(ellipse1)
graphic1.add(ellipse2)
graphic1.add(ellipse3)
graphic1.remove(ellipse2)

graphic2.add(ellipse4)

graphic.add(graphic1)
graphic.add(graphic2)

graphic.print()

Reference document

wiki - Composite_pattern