Tải bản đầy đủ - 0 (trang)
13-13. Perform Lazy Object Initialization

13-13. Perform Lazy Object Initialization

Tải bản đầy đủ - 0trang

CHAPTER 13 ■ COMMONLY USED INTERFACES AND PATTERNS



How It Works

The .NET Framework performs eager initialization by default, which means that types are initialized as

soon as they are created. By contrast, lazy initialization lets you defer object initialization until you need

to access one of the members of your type. Eager initialization tends to create applications that create

lots of objects when they start, even though the objects themselves may not be used for some time—this

can consume resources unnecessarily and slow down your application, at least until all of the objects are

created. To use lazy initialization, you simply pass your normal object instantiation as a delegate

argument to the constructor of the System.Lazy class, so that

MyDataType mytype = new MydataType();

becomes

Lazy myType = new Lazy new MyDataType());

In order to access the type within the Lazy instance, you call the Value property—the first time that

Value is called, the type will be initialized—in this way, you can defer initializing your object until you

need to use it.



The Code

The following example defines a type called MyDataType, which has a constructor and a method called

sayHello. The Main method called when the application starts creates an instance of MyDataType using

eager initialization, prints out a message simulating performing other tasks, and then calls sayHello.

This process is then repeated using lazy initialization. The result is that the constructor is called as soon

as the object reference is created using eager initialization, whereas the constructor is not called until

the sayHello method is invoked when using lazy initialization.

using

using

using

using



System;

System.Collections.Generic;

System.Linq;

System.Text;



namespace Apress.VisualCSharpRecipes.Chapter13

{

class Recipe13_13

{

static void Main(string[] args)

{

// Create an instance using eager initialization.

MyDataType eagerInstance = new MyDataType(false);

Console.WriteLine("...do other things...");

eagerInstance.sayHello();

Lazy lazyInstance = new Lazy(()

=> new MyDataType(true));

Console.WriteLine("...do other things...");

lazyInstance.Value.sayHello();



672



www.it-ebooks.info



CHAPTER 13 ■ COMMONLY USED INTERFACES AND PATTERNS



// Wait to continue.

Console.WriteLine(Environment.NewLine);

Console.WriteLine("Main method complete. Press Enter");

Console.ReadLine();

}

}

class MyDataType

{

public MyDataType(bool lazy)

{

Console.WriteLine("Initializing MyDataType - lazy instance: {0}", lazy);

}

public void sayHello()

{

Console.WriteLine("MyDataType Says Hello");

}

}

}



13-14. Use Optional Parameters

Problem

You need to define a method with optional parameters.



Solution

Supply a default value for the parameters you wish to make optional when defining your method.



How It Works

The optional parameters feature allows you to simplify a common programming pattern, where several

slightly different methods exist to allow a caller to use default values, such as the following:

void printMessage()

{

printMessage("Adam");

}

void printMessage(string from)

{

printMessage(from, "Hello");

}



673



www.it-ebooks.info



CHAPTER 13 ■ COMMONLY USED INTERFACES AND PATTERNS



void printMessage(string from, string message)

{

printMessage(from, message, false);

}

void printMessage(string from, string message, bool urgent)

{

// Do something.

}

This approach allows callers of the method to rely on default values—this helps to simplify the code

of the calling classes. C# supports optional parameters so that you can achieve the same effect with only

one method in your class—you do this by setting the default values when defining the parameters—for

example:

void printMessage(string from = "Adam", string message = "Hello",

bool urgent = false)

Optional parameters must be defined after normal parameters.



The Code

The following example defines a method with three optional parameters:

using

using

using

using



System;

System.Collections.Generic;

System.Linq;

System.Text;



namespace Apress.VisualCSharpRecipes.Chapter13

{

class Recipe13_14

{

static void Main(string[] args)

{

printMessage();

printMessage("Allen");

printMessage("Bob", "Goodbye");

printMessage("Joe", "Help", true);

// Wait to continue.

Console.WriteLine(Environment.NewLine);

Console.WriteLine("Main method complete. Press Enter");

Console.ReadLine();

}

static void printMessage(string from = "Adam", string message = "Hello",

bool urgent = false)

{



674



www.it-ebooks.info



CHAPTER 13 ■ COMMONLY USED INTERFACES AND PATTERNS



Console.WriteLine("From: {0}, Urgent: {1}, Message: {2}",

from, message, urgent);

}

}

}



13-15. Add a Method to a Type Without Modifying It

Problem

You want to add a method to a type without modifying it, most likely because you didn’t write the type

you want to modify.



Solution

Implement and call a custom extension method.



How It Works

Extension types allow you to extend a type by providing new methods in a separate class file and

associating them with the type you wish to apply them to. The main need for this C# feature is when you

want to associate new features with a type that you didn’t write—one from the .NET Framework class

library, for example. To create an extension method, start by creating a static class—a static class has the

keyword static before class in the declaration. A static class is like a regular class, except the class

cannot be instantiated and all of the methods must be static.

Add a static method to the static class with the name and result type you require. The first

parameter of the method must be of the type that you wish to extend and be prefaced with the

word this.

Implement the method body, performing the tasks you require. The parameter you prefaced with

this represents the instance of the type you have extended on which your method has been invoked. For

example, suppose we define an extension for string like this:

public static int countVowels(this string str)

The str parameter is the string instance that the extension has been invoked to process. To use an

extension method, you must ensure that the namespace in which you created the static class is available

to the calling class with the using keyword, just as you would for any other namespace. Then you simply

call the extension method as though it is an instance method of the type you have extended—for

example:

String mystring = "Hello";

Mystring.countVowels();

Note that you don’t need to provide the first argument you declared for your extension method (the

one prefaced with this).



675



www.it-ebooks.info



CHAPTER 13 ■ COMMONLY USED INTERFACES AND PATTERNS



The Code

The following example defines two extension methods for the string type in the namespace

Apress.VisualCSharpRecipes.Chapter13.Extensions:

using

using

using

using

using



System;

System.Collections.Generic;

System.Linq;

System.Text;

Apress.VisualCSharpRecipes.Chapter13.Extensions;



namespace Apress.VisualCSharpRecipes.Chapter13.Extensions

{

public static class MyStringExtentions

{

public static string toMixedCase(this String str)

{

StringBuilder builder = new StringBuilder(str.Length);

for (int i = 0; i < str.Length; i += 2)

{

builder.Append(str.ToLower()[i]);

builder.Append(str.ToUpper()[i + 1]);

}

return builder.ToString();

}

public static int countVowels(this String str)

{

char[] vowels = { 'a', 'e', 'i', 'o', 'u' };

int vowelcount = 0;

foreach (char c in str)

{

if (vowels.Contains(c))

{

vowelcount++;

}

}

return vowelcount;

}

}

}

namespace Apress.VisualCSharpRecipes.Chapter13

{

class Recipe13_15

{

static void Main(string[] args)

{

string str = "The quick brown fox jumped over the...";

Console.WriteLine(str.toMixedCase());

Console.WriteLine("There are {0} vowels", str.countVowels());



676



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

13-13. Perform Lazy Object Initialization

Tải bản đầy đủ ngay(0 tr)

×