工廠設(shè)計(jì)模式
- 很容易改變的類創(chuàng)建的對(duì)象或我們創(chuàng)建這些對(duì)象的方式。
- 很容易用有限的資源限制的創(chuàng)建對(duì)象,例如,我們只能有N個(gè)對(duì)象。
- 很容易生成統(tǒng)計(jì)數(shù)據(jù)對(duì)創(chuàng)建的對(duì)象呻纹。
例子
各種類,如 ThreadPoolExecutor,使用構(gòu)造函數(shù)接受 ThreadFactory作為參數(shù)鸽心。這個(gè)工廠當(dāng)執(zhí)行程序創(chuàng)建一個(gè)新的線程使用。使用ThreadFactory您可以自定義線程創(chuàng)建的執(zhí)行者,他們有適當(dāng)?shù)木€程名稱居暖、優(yōu)先級(jí),甚至他們還可以守護(hù)進(jìn)程。
class Task implements Runnable
{
@Override
public void run()
{
try
{
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public class CustomThreadFactory implements ThreadFactory
{
private int counter;
private String name;
private List<String> stats;
public CustomThreadFactory(String name)
{
counter = 1;
this.name = name;
stats = new ArrayList<String>();
}
@Override
public Thread newThread(Runnable runnable)
{
Thread t = new Thread(runnable, name + "-Thread_" + counter);
counter++;
stats.add(String.format("Created thread %d with name %s on %s \n", t.getId(), t.getName(), new Date()));
return t;
}
public String getStats()
{
StringBuffer buffer = new StringBuffer();
Iterator<String> it = stats.iterator();
while (it.hasNext())
{
buffer.append(it.next());
}
return buffer.toString();
}
public static void main(String[] args)
{
CustomThreadFactory factory = new CustomThreadFactory("CustomThreadFactory");
Task task = new Task();
Thread thread;
System.out.printf("Starting the Threads\n\n");
for (int i = 1; i <= 10; i++)
{
thread = factory.newThread(task);
thread.start();
}
System.out.printf("All Threads are created now\n\n");
System.out.printf("Give me CustomThreadFactory stats:\n\n" + factory.getStats());
}
}