zoukankan      html  css  js  c++  java
  • 面向对象编程笔记--static

        通过static方法,提供静态的不需要实例化即可访问的方法或属性。所有的调用者可以使用同一个类(不实例化)或对象(只实例化一次),可以应用的场景:

        1)各个调用者共享数据,协同工作。

        2)对象只可以实例化一次。

        3)被调用对象的生命周期 与调用者无关。或者说,该对象有全局的生命周期,持续工作,提供给调用者的只是一个接口。

        类的实例由类自己来维护,对外提供一个 取实例的一个方法。

        典型代码:

    public class TestClass
    {
        //维护的实例
        private static TestClass instance;
        //对外提供的get实例的静态方法
        public static TestClass Instance
        {
            get
            {
                if (instance == null)
                    instance = new TestClass();
                return instance;
            }
        }
    }

        应用举例:

        WPF中关于DependencyProperty的定义

    /*
    *    两种使用方式
    *        1)以总类的形式利用Dictionary,记录所有通过该类的静态注册方法注册的属性
    *        2)生成新的对象
    *
    */ 
    public class DependencyProperty
    {
        internal static Dictionary<object, DependencyProperty> RegisteredDps = new Dictionary<object, DependencyProperty>();
        internal string Name;
        internal object Value;
        internal object HashCode;
        //构造函数
        private DependencyProperty(string name, Type propertyName, Type ownerType, object defaultValue)
        {
            this.Name = name;
            this.Value = defaultValue;
            this.HashCode = name.GetHashCode() ^ ownerType.GetHashCode();
        }
        //注册函数
        public static DependencyProperty Register(string name, Type propertyType, Type ownerType, object defaultValue)
        {
            DependencyProperty dp = new DependencyProperty(name, propertyType, ownerType, defaultValue);
            RegisteredDps.Add(dp.HashCode, dp);
            return dp;
        }
    }
  • 相关阅读:
    JS 数组排序
    曾经跳过的坑------replace、替换斜杠反斜杠、时间格式化处理
    List排序、集合排序
    git远程覆盖本地的
    整理日期,整理时间段,将日期集合整理为时间段
    当数据库查询in使用超过1000个的处理方式,in超过1000的问题
    oracle一些语法
    idea中git操作
    idea鼠标放上去查看注释,idea查看注释
    idea更新git远程代码,查看代码改动了哪些
  • 原文地址:https://www.cnblogs.com/the-owl/p/5546845.html
Copyright © 2011-2022 走看看