Return directory]
Chinese people have the tradition of paper-cutting, especially in the face of red and white events, people often use a variety of paper-cutting works, such as the Red dragonfly, paper-cutting, cars, houses, and so on. Different items must be cut by different types of paper. For example, no one cut the red and bright "yellow" text with the Earth-yellow horse and dung paper, and no one cut the paper money that spreads across the mountains with A4 paper. Paper is divided into many categories, and there are many types in each category. There may be many models in each category. Chinese people are very careful about the choice of paper, there are only a few types of scissors. No one requires that each type of paper correspond to a pair of scissors. for paper-cutting, scissors are used for daily purposes, the tailor's scissors are too rough and the doctor's surgical scissors are too expensive.
This is the applicable scenario of Prototype mode: You can use the same tool class to create different object instances, and the classes of these object instances all inherit from the same base class. The tool class does not know how to create and process objects. If you create a tool class for each object, there will be a lot of repeated code and similar objects, which is not conducive to development and maintenance. A better way is to create a new class object by copying or cloning the tool class. We call this base class Prototype, all subclasses inherited from this base class implement a clone method, so that this tool class can "clone" all types of subclass objects. Let's take a look at the Code:
1: using System;
2:
3: namespace Autumoon.DesignPatterns.Prototype
4: {
5: public abstract class PaperPrototype
6: {
7: public abstract PaperPrototype SelfClone();
8: }
9:
10: public class RicePaper : PaperPrototype
11: {
12: public override PaperPrototype SelfClone()
13: {
14: return (PaperPrototype)MemberwiseClone();
15: }
16: }
17:
18: public class Forfex
19: {
20: public PaperPrototype InternalPrototype { get; set; }
21:
22: public void Cut()
23: {
24: PaperPrototype paper = this.InternalPrototype.SelfClone();
25:
26: // TODO: Do some cut operation.
27: }
28: }
29: }
As a result, Forfex (scissors), a tool class, does not have to worry about its uncertain type. Instead, it only needs to focus on Cut operations.
1: static void Main(string[] args)
2: {
3: RicePaper ricePaper = new RicePaper();
4: Forfex forfex = new Forfex();
5: forfex.InternalPrototype = ricePaper;
6: forfex.Cut();
7:
8: Console.ReadLine();
9: }