/// <summary> /// 拿取實體化物件 /// </summary> /// <returns></returns> public static LazyObject GetInstance() { if (instance == null) { instance = new LazyObject(); } return(instance); }
protected void ProcessIndexSetterForMostCases(IVirtualListServiceDependencies services, IVirtualListContext ctx, int index, object value) { ValidateIndexOutOfRange(ctx.pageIndexes, index); // Get the page's unique id that is located the index string pageUniqueID = ctx.pageIndexes[index] as string; // Loads the page from storage or from cache Page page = services.Pager.LoadPage(pageUniqueID); // Get the initial index of the corresponding page int pageIndex = ctx.initialIndexDictionary[page.UniqueID]; // Get the real index inside the page int indexInsidePage = index - pageIndex; // Get the object related with the index LazyObject obj = (LazyObject)page.GetAtSafe(indexInsidePage); var stateobject = obj.Target as IStateObject; if (stateobject != null) { //Detach the reference services.ReferenceManager.UnSubscribe(page, stateobject.UniqueID); } var elementToSet = value as IStateObject; if (elementToSet != null) { if (!services.StateManager.IsStateObjectAttached(elementToSet)) { services.StateManager.PromoteObject(elementToSet, services.UniqueIdGenerator.GetPageItemUniqueID()); page.SetAtSafe(indexInsidePage, GetLazyObjectFor(elementToSet, services.StateManager)); } else if (!services.StateManager.IsStateObjectAllAttached(elementToSet)) { page.SetAtSafe(indexInsidePage, GetLazyObjectFor(elementToSet, services.StateManager)); } else { //Is all branches attached page.SetAtSafe(indexInsidePage, GetLazyObjectFor(elementToSet, services.StateManager)); } //Subscribe to IReferenceManager in order to listen reference changes updates. SubscribeToReferenceManager(services.ReferenceManager, page, elementToSet); } else { //Assign the new value page.SetAtSafe(indexInsidePage, GetLazyObjectFor(value, services.StateManager)); } services.StateManager.MarkAsDirty(page, "StoredObjects"); }
protected object ProcessIndexGetterForMostCases(IVirtualListServiceDependencies services, IVirtualListContext ctx, int index) { ValidateIndexOutOfRange(ctx.pageIndexes, index); // Get the page's unique id that is located the index string pageUniqueID = ctx.pageIndexes[index] as string; // Loads the page from storage or from cache Page page = services.Pager.LoadPage(pageUniqueID); // Get the initial index of the corresponding page int pageIndex = ctx.initialIndexDictionary[page.UniqueID]; // Get the real index inside the page int indexInsidePage = index - pageIndex; // Get the object related with the index LazyObject obj = (LazyObject)page.GetAtSafe(indexInsidePage); return(obj.Target); }
public LazyObject GetLazyFactoryObject(LazyObjectType name) { //yes, i know it is illiterate and inaccurate LazyObject noGoodSomeBitch; //retrieves LazyObjectType from list via out, else creates one and adds it to list if (!_LazyObjectList.TryGetValue(name, out noGoodSomeBitch)) { noGoodSomeBitch = new LazyObject(); noGoodSomeBitch.Name = name; noGoodSomeBitch.Result = this.Result(name); _LazyObjectList.Add(name, noGoodSomeBitch); } return(noGoodSomeBitch); }
public static void Object() { // Arrange var count = 0; var lazyString = new LazyObject <string>(() => { count++; return("test"); }); Assert.Equal(0, count); Assert.False(lazyString.Loaded); // Act var result = lazyString.Object; // Assert Assert.Equal("test", result); Assert.Equal(1, count); Assert.True(lazyString.Loaded); }
/// <summary> /// Double-Checked Locking (多執行緒情況下) /// 拿取實體化物件 /// </summary> /// <returns></returns> public static LazyObject GetInstanceBySync() { if (instance == null) { // 防範多執行緒的情況,確保不會同時進入而造成產生多物件 lock (syncRoot) { // 確保只會實體化一次,實體化過的就直接返回 if (instance == null) { instance = new LazyObject(); } } } return(instance); }
static void Main(string[] args) { AbstractFactoryClient client = new AbstractFactoryClient(MANUFACTURES.PRODUCT1FACTORY); client.ProductList(); client = new AbstractFactoryClient(MANUFACTURES.PRODUCT2FACTORY); client.ProductList(); IBuilder builder1 = new ConcreteBuilder1(); Console.WriteLine($"New Product created: {Manufacture.Construct(builder1)}"); builder1 = new ConcreteBuilder2(); Console.WriteLine($"New Product created: {Manufacture.Construct(builder1)}"); Creator creator = new Creator(); IProduct product; product = creator.GetProduct(PRODUCT.TYPE1); Console.WriteLine(product.Description); product = creator.GetProduct(PRODUCT.TYPE2); Console.WriteLine(product.Description); LazyObject.Get("first"); LazyObject.Get("second"); LazyObject.ShowAll(); LazyObject.Get("third"); LazyObject.Get("first"); LazyObject.ShowAll(); Person personClient = new Client() { FirstName = "Ivan", SecondName = "Ivanov", OrdersCount = 5 }; Person personEmployee = new Employee() { FirstName = "Petr", SecondName = "Petrov", Salary = 1000 }; ToStringVisitor visitor = new ToStringVisitor(); Console.WriteLine(visitor.DynamicVisit(personClient)); Console.WriteLine(visitor.DynamicVisit(personEmployee)); Console.WriteLine("Complete"); Console.ReadKey(); }
public SynchronizedSymmetricAlgorithmContext(SymmetricAlgorithm algorithm) { m_algorithm = algorithm; m_encryptor = new LazyObject <ICryptoTransform>(() => { lock (m_algorithm) { return(m_algorithm.CreateEncryptor()); } }); m_decryptor = new LazyObject <ICryptoTransform>(() => { lock (m_algorithm) { return(m_algorithm.CreateDecryptor()); } }); }
protected void ProcessRemoveAtForMostCases(IVirtualListServiceDependencies services, IVirtualListContext ctx, int index) { ValidateIndexOutOfRange(ctx.pageIndexes, index); // Get the page's unique id that is located the index string pageUniqueID = ctx.pageIndexes[index] as string; // Loads the page from storage or from cache Page page = services.Pager.LoadPage(pageUniqueID); // Get the initial index of the corresponding page int pageIndex = ctx.initialIndexDictionary[page.UniqueID]; // Get the real index inside the page int indexInsidePage = index - pageIndex; // Get the object related with the index LazyObject obj = (LazyObject)page.GetAtSafe(indexInsidePage); var stateobject = obj.Target as IStateObject; if (stateobject != null) { // Unsubscribes the object from the page's reference table services.ReferenceManager.UnSubscribe(page, stateobject.UniqueID); } // Removes the object from the stored objects page.RemoveAtSafe(indexInsidePage); // Updates the indexes of the Initial Index Dictionary UpdateIndexDictionary(page, pageIndex, -1, ctx.pageIndexes, ctx.initialIndexDictionary); ctx.pageIndexes.RemoveAt(index); //Mark the page as dirty in order to be serialized again services.StateManager.MarkAsDirty(page, "StoredObjects"); }
private void ReadObjects() { Scope sc = parser.RootScope; Element eobjects = sc["Objects"]; if (eobjects == null || eobjects.Compound == null) { throw (new Exception("no Objects dictionary found")); } objects[0] = new LazyObject(0, eobjects, this); Scope sobjects = eobjects.Compound; foreach(var el_ in sobjects.Elements) { foreach (var el in el_.Value) { // extra ID List<Token> tok = el.Tokens; if (tok.Count == 0) { throw (new Exception("expected ID after object key")); } string err; var id = Parser.ParseTokenAsID(tok[0], out err); if (!string.IsNullOrEmpty(err)) { throw (new Exception(err)); } // id=0 is normally implicit if (id == 0) { throw (new Exception("encountered object with implicitly defined id 0")); } if (objects.ContainsKey(id)) { Console.Error.WriteLine("encountered duplicate object id, ignoring first occurrence"); } objects[id] = new LazyObject(id, el, this); // grab all animation stacks upfront since there is no listing of them if (el_.Key == "AnimationStack") { animationStacks.Add(id); } } } }
public SymmetricAlgorithmContext(SymmetricAlgorithm algorithm) { m_algorithm = algorithm; m_lazyEncryptor = new LazyObject <ICryptoTransform>(() => m_algorithm.CreateEncryptor()); m_lazyDecryptor = new LazyObject <ICryptoTransform>(() => m_algorithm.CreateDecryptor()); }
private object[] GetMultiObjectsFormRequest(HttpContext context, ActionDescription action) { HttpRequest request = context.Request; string xml = request.ReadInputStream(); XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNode root = doc.LastChild; //if( root.ChildNodes.Count != action.Parameters.Length ) // throw new ArgumentException("客户端提交的数据项与服务端的参数项的数量不匹配。"); object[] parameters = new object[action.Parameters.Length]; LazyObject <ModelBuilder> builder = new LazyObject <ModelBuilder>(); for (int i = 0; i < parameters.Length; i++) { FromBodyAttribute bodyAttr = action.Parameters[i].GetMyAttribute <FromBodyAttribute>(false); if (bodyAttr != null) { // 当前参数需要从整体请求体中反序列化得到参数值 parameters[i] = GetObjectFromRequest(context, action); } else { string name = action.Parameters[i].Name; XmlNode node = (from n in root.ChildNodes.Cast <XmlNode>() where string.Compare(n.Name, name, StringComparison.OrdinalIgnoreCase) == 0 select n).FirstOrDefault(); if (node != null) { try { object parameter = null; Type destType = action.Parameters[i].ParameterType.GetRealType(); if (destType.IsSupportableType()) // 如果是简单类型,就不需要反序列化 { parameter = builder.Instance.StringToObject(node.InnerText, destType); } else { // 复杂类型的参数,就使用反序列化 parameter = XmlDeserialize(node.OuterXml, destType, request.ContentEncoding); } parameters[i] = parameter; } catch (Exception ex) { throw new InvalidCastException("数据转换失败,当前参数名:" + name, ex); } } else { // 再次尝试从HTTP上下文中获取 parameters[i] = GetParameterFromHttp(context, action.Parameters[i]); } } } return(parameters); }