Prototype模式(原型模式)

模式简介

原型模式通常用于克隆一个对象,当一个对象进行创建时需要传递许多参数,但是很多参数我们可以与之前的对象保持一致,那么就可以通过原型模式来实现对象克隆。

模式UML图

代码示例(C#)

提示:可在本栏目的资源篇“设计模式代码示例合集”下载所有完整代码资源。

    public class Cube : IConleable<Cube>
    {
        public string name;
        public string color;
        public string material;
        public float width;
        public float height;
        public float length;
        public Position position;

        public Cube(string p_name, string p_color, string p_material, float p_width, float p_height, float p_length, Position p_position)
        {
            name = p_name;
            color = p_color;
            material = p_material;
            width = p_width;
            height = p_height;
            length = p_length;
            position = p_position;
        }
        public Cube Clone()
        {
            Position v_position = new Position(position.x, position.y, position.z);
            return new Cube(name, color, material, width, height, length, v_position);
        }

        public override string ToString()
        {
            string v_str = "";
            v_str += "【Cube:" + name + "】\n";
            v_str += "--------------------------\n";
            v_str += "[Color]:" + color + "\n";
            v_str += "[Material]:" + material + "\n";
            v_str += "[Width]:" + width + "\n";
            v_str += "[Height]:" + height + "\n";
            v_str += "[Length]:" + length + "\n";
            v_str += "--------------------------\n";
            return v_str;
        }
    }

    public class Position
    {
        public float x;
        public float y;
        public float z;
        public Position(float p_x, float p_y, float p_z) { x = p_x; y = p_y; z = p_z; }
    }

    public interface IConleable<T>
    {
        public T Clone();
    }

    //测试代码
    public void Test()
    {
        Cube cube1 = new Cube("cube1", "Blue", "Wood", 4, 4, 4, new Position(3.1f, 2.2f, 4.2f));
        Cube cube2 = cube1.Clone();
        cube1.color = "Black";
        cube2.name = "cube2";
        Console.WriteLine(cube1);
        Console.WriteLine(cube2);
        Console.WriteLine(cube1 == cube2);
    }

代码解说

我们要求具备克隆功能的类实现ICloneable接口的Clone方法,在Clone方法中对所有参数进行默认赋值,然后返回一个对象,这样当我们需要克隆一个对象时,直接调用其Clone方法即可,如果想要对特定参数进行赋值,直接通过返回的对象直接进行赋值即可,这里需要注意的是,我们在编写Clone方法时,对于非数值类型的参数要注意其赋值,例如我们这里的Position类型参数,需要重新new一个Position对象并对其进行赋值,不能像值类型那样直接传递,引用类型传递的是引用,也就是如果我们把cube1的position直接当作参数传递给克隆对象cube2的话,则二者的position参数是指向的同一个内存地址,所以编写克隆方法时要注意这种浅拷贝和深拷贝的问题。

如果这篇文章对你有帮助,请给作者点个赞吧!

猜你喜欢

转载自blog.csdn.net/hgf1037882434/article/details/128380674
今日推荐